this is my first flutter JSON example, I tried to fetch data from the json link and display the titles as list view
I used this code to write mine with some changes .. in the link he has results
array in mine I haven't so I left the data = resBody[" "];
empty is that right?
also, I got this error with the flutter HTTP request and don't really what to do
any help, please?
Dart Error: Unhandled exception:
type 'String' is not a subtype of type 'int' of 'index'
this is my code
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(
home: ToDo(),
));
}
class ToDo extends StatefulWidget {
@override
ToDoState createState() => ToDoState();
}
class ToDoState extends State<ToDo> {
final String url = "https://jsonplaceholder.typicode.com/todos";
List data;
Future<String> getTitle() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
setState(() {
var resBody = json.decode(res.body);
data = resBody[" "];
});
return "Success!";
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title List"),
backgroundColor: Colors.amber,
),
body: ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text("Title: "),
Text(data[index]["title"],
style: TextStyle(
fontSize: 18.0, color: Colors.black87)),
],
)),
),
],
),
),
);
},
),
);
}
@override
void initState() {
super.initState();
this.getTitle();
}
}
Your getTitle
methods needs to be changed to the following:
Future<String> getTitle() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
setState(() {
var resBody = json.decode(res.body);
data = resBody; //This line changed from data = resBody[" "];
});
return "Success!";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With