【问题标题】:How do I collect a loop through a list from http in JSON如何通过 JSON 中的 http 列表收集循环
【发布时间】:2019-10-08 16:37:30
【问题描述】:

我正在学习 Flutter,但我已经做了一段时间的开发人员。我正在使用我的一个网站使其无头,并尝试将数据输入我的应用程序。

我正在学习这个例子:https://flutter.dev/docs/cookbook/networking/fetch-data

在此示例中,他们获取单个用户。如果有多个用户,我有点不知道这会如何改变。

例如,如果数据的结构更像:

{'users':[{'userId':1,'id':1,'title':'title1','body':'This is Body 1'},{'userId':2,'id':2,'title':'title2','body':'This is Body 2'}]

您如何使用教程中的方法捕捉到这一点?你怎么能遍历列表并显示一些简单的东西,比如标题和正文?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    使用教程中的示例,您可以这样做:

    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);
      }
    }
    

    这是教程中的 Post 类:

    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'],
        );
      }
    }
    

    要显示标题和正文列表,您可以像这样更改教程中的 FutureBuilder:

    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();
      },
    ),
    

    我推荐你这篇文章来了解更多关于解析 JSON: Parsing complex JSON in Flutter

    此外,您可以在此处找到有关如何进行手动序列化和自动序列化的更多信息: JSON and serialization

    【讨论】:

    • 我收到错误消息:编译器消息:lib/main.dart:59:23:错误:最终字段“用户”未初始化。尝试在声明或每个构造函数中初始化字段。最终的 Future 用户;
    • 您应该在 MyApp 的构造函数中为 this.users 更改 this.post,然后在 runApp 中为调用 MyApp 的用户更改 post,您还需要在 fetchPost 中返回 Future () 使用模拟响应可能代替教程中使用的具有您建议的 JSON 结构的 api
    • 我不明白 this.post 在调用 api 时是如何工作的。我了解序列化,但是当我尝试打印测试时,它不起作用。
    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2020-07-08
    • 1970-01-01
    • 2017-05-12
    • 2013-08-19
    • 1970-01-01
    相关资源
    最近更新 更多