Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

flutter - How do I collect a loop through a list from http in JSON

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...