【发布时间】: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")并告诉我你得到了什么吗?