Reputation: 769
I'm learning Flutter, but I've been a dev for a while now. I'm using one of my sites to make it headless, and trying to feed the data into my app.
I'm following the example: https://flutter.dev/docs/cookbook/networking/fetch-data
In this example, they fetch a single user. I'm a bit lost on how this would change if there were multiple users.
For example, if the data was structured more like:
{'users':[{'userId':1,'id':1,'title':'title1','body':'This is Body 1'},{'userId':2,'id':2,'title':'title2','body':'This is Body 2'}]
How could you capture that using the method in the tutorial? How could you loop through the list and display something simple like the title and bodies?
Upvotes: 2
Views: 1599
Reputation: 10963
Using the example from the tutorial, you could do this:
class Users {
final List<Post> users;
Users({this.users});
factory Users.fromJson(Map<String, dynamic> json) {
List<Post> tempUsers = [];
for (int i = 0; i < json['users'].length; i++) {
Post post = Post.fromJson(json['users'][i]);
tempUsers.add(post);
}
return Users(users: tempUsers);
}
}
And this is the Post class from the tutorial:
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
To show a list of titles and bodies, you could change the FutureBuilder on the tutorial like this:
final Future<Users> users;
...
FutureBuilder<Users>(
future: users,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.users.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Text('Title: ${snapshot.data.users[index].title}'),
Text('Body: ${snapshot.data.users[index].body}'),
],
);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
I recommend you this article to learn more about parsing JSON: Parsing complex JSON in Flutter
Also, here you can find more information about how to do manual serialization and automated serialization: JSON and serialization
Upvotes: 3