【发布时间】:2021-07-30 21:11:21
【问题描述】:
我正在尝试从 API 中获取数据。只是为了测试我使用的是 API URL:https://jsonplaceholder.typicode.com/todos/1,它具有以下 JSON 对象:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
我在网上按照一个示例进行了几乎完全调整以匹配我想要的工作流程,但下面的 snapshot.hasData 返回 false。
class Home extends StatelessWidget {
final String accountNum;
Home(this.accountNum);
final String apiUrl = "https://jsonplaceholder.typicode.com/todos/";
Future<Map<String, dynamic>> fetchData() async {
//accountNum below is passed from a previous screen, in this case I pass '1'
//I printed it to make sure that '1' is passed and it is correct
var result = await http.get(apiUrl+accountNum);
//I printed the below and it also gave me the json from the api
//print(json.decode(result.body));
return json.decode(result.body);
}
String _MeterNum(dynamic account){
return account['title'];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Account Data'),
),
body: Container(
child: FutureBuilder<Map<String, dynamic>>(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
print(_MeterNum(snapshot.data[0]));
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index){
return
Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(snapshot.data[index]['picture']['large'])),
//I realize this will just show the same thing
//but I was just keeping the format of the example I was following
title: Text(_MeterNum(snapshot.data[index])),
subtitle: Text(_MeterNum(snapshot.data[index])),
trailing: Text(_MeterNum(snapshot.data[index])),
)
],
),
);
});
}else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
}
返回的是CircularProgressIndicator() 到模拟器屏幕,表明snapshot.hasData 是假的。我没有在控制台或任何东西中收到任何错误,所以我不确定如何继续。
---编辑--- 使用评论者的建议对上面的代码进行了更改:
将返回类型从 Future
更改为 Future
现在我收到以下错误:
以下 NoSuchMethodError 被抛出构建 FutureBuilder>(脏,状态: _FutureBuilderState
在 null 上调用了方法“[]”。收件人:空
尝试调用:[] ("title")
【问题讨论】:
-
你的响应是一个 json 对象,你正在处理 List
这就是问题 -
添加到上面的评论(将返回类型从 Future
- > 更改为 Future
-
现在我得到一个错误。我已在原帖中编辑并添加。
标签: android ios api flutter dart