【问题标题】:Flutter http get json dataFlutter http 获取json数据
【发布时间】:2021-01-14 23:41:52
【问题描述】:

我在获取数据时遇到了困难。我对 Flutter 很陌生,虽然我阅读了文章,但我无法克服这个问题。我能够单独获取数据,但我无法将其置于循环中。代码如下。

    Future<List<Post>> getPosts() async {
  var jsonData = await http.get("https://example.com/api/posts.php");
  final jsonResponse = json.decode(jsonData.body);
  Match postList= Post.fromJsonMap(jsonResponse);
  return (jsonResponse as List)
      .map((postList) => Post.fromJsonMap(postList))
      .toList();
  //print("post" + postList.result[1].home);
}

当我运行打印方法时,我可以打印数据。但是,当我将其发送给 futurebuilder 时,数据并没有到来。

body: FutureBuilder(
          future: getPosts(),
          builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
            if (snapshot.hasData) {
              print("test");
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(snapshot.data[index].result[index].home),
                      subtitle: Text(snapshot.data[index].result[index].title),
                      leading: CircleAvatar(
                        child: Text(
                            snapshot.data[index].result[index].id.toString()),
                      ),
                    );
                  });
            } else {
              return Center(child: CircularProgressIndicator());
            }
          }),

注意:我以代码为例:https://github.com/emrealtunbilek/flutter_json_http/blob/master/lib/remote_api.dart

【问题讨论】:

  • 你能用print(snapshot.data) 代替print("test") 并告诉我你得到了什么吗?

标签: json flutter http dart


【解决方案1】:

尝试添加额外的 if 分支

} else if (snapshot.hasError) {
    print(snapshot.error);
} else {

【讨论】:

  • 在构建 FutureBuilder>(dirty, state: _FutureBuilderState>#a36f2) 时抛出以下断言:构建函数返回 null。
【解决方案2】:

您可以使用JsonToDart 解析数据并转换为您的模型

【讨论】:

  • 我使用 Json 创建了我的模型来飞镖,但数据没有来。 JSON数据有问题吗?我可以从其他来源提取数据。 (jsonplaceholder)
  • 我使用的JSON类型是:{"success":true,"result":[{"id":"3970","home":"Test","title":"TestTitle "}],"premium":true,"type":null}
  • 使用 jsonDecode(stringData);并将其传递给 model.fromJson();
猜你喜欢
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 2020-11-16
  • 2021-08-05
  • 2018-11-29
  • 2021-01-18
  • 1970-01-01
相关资源
最近更新 更多