我刚接触 flutter 并试图从 api 获取数据进行测试,但我有一些错误,这是我试图从中获取数据并将其显示到 FutureBuilder 中的链接,但我无法获得任何人的信息可以帮我!
这是我的代码:
class _MyHomePageState extends State<MyHomePage> {
final String apiUrl = "https://jsonplaceholder.typicode.com/users";
Future<List<Post>> fetchData() async {
http.Response res = await http.get(apiUrl);
if (res.statusCode == 200) {
var obj = json.decode(res.body);
List<Post> posts = new List<Post>();
for(int i=0;i>obj.length;i++){
Post post = Post.fromJson(obj[i]);
posts.add(post);
print(post.name);
}
return posts;
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder(
future: fetchData(),
builder: (ctx,snapShot){
if(snapShot.connectionState == ConnectionState.waiting){
return CircularProgressIndicator();
}else{
return ListView.builder(
itemBuilder: (context,index){
return ListTile(
leading: CircleAvatar(),
title: Text(""),
subtitle: Text(""),
);
});
}
},
),
),
);
}
}
这是我将 api json 转换为 dart 的链接
答案 0 :(得分:2)
改变
for(int i=0;i>obj.length;i++){
Post post = Post.fromJson(obj[i]);
posts.add(post);
print(post.name);
}
return posts;
到
var response = List<Post>.from(obj.map((i) => Post.fromJson(i)));
return response;
之后,将 itemCount: snapShot.data.length
添加到您的 ListView.builder