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

前端 未结 1 480
心在旅途
心在旅途 2020-12-12 02:28

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 t

相关标签:
1条回答
  • 2020-12-12 02:56

    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

    0 讨论(0)
提交回复
热议问题