问题描述
我使用 Flutter 构建了一个应用程序,该应用程序从 api 获取信息并将其显示在列表磁贴中。我想启用 ontap 功能,以便每当有人点击列表磁贴中的项目时,它都会打开另一个页面并显示该信息 这是列表磁贴代码
itemCount: prospectList.data.length,itemBuilder: (context,i) {
final x = prospectList.data[i];
return ListTile(
title: Text(x.firstname),subtitle: Text(x.lastname),leading: CircleAvatar(
backgroundColor: Colors.green,child: Text(x.firstname[0],style: TextStyle(
color: Colors.white,fontSize: 20.0,)),),onTap: () => Navigator.push(
context,MaterialPageRoute(
builder: (context) => CustomerInfo())),);
我收到此错误
The following NoSuchMethodError was thrown building CustomerInfo(dirty,dependencies: [_InheritedTheme,_LocalizationsScope-[GlobalKey#5a50d]]):
The getter 'data' was called on null.
Receiver: null
Tried calling: data
The relevant error-causing widget was
CustomerInfo
api 调用
Future<String> _fetchData() async {
setState(() => loading = true);
final response = await http.get('run.mocky.io/v3/ad6092cd-3b2d-4b62-92f1-4198f697f3d3');
if (response.statusCode == 200) {
final datas = jsonDecode(response.body);
final prospectListFromJson = ProspectList.fromJson(datas);
setState(() {
prospectList = prospectListFromJson;
loading = false;
});
} else {
print(response.statusCode);
}
}
@override
void initState() {
super.initState();
_fetchData();
}
解决方法
我建议使用 FutureBuilder
。
Future<ProspectList> _fetchData() async {
final response = await http.get('run.mocky.io/v3/ad6092cd-3b2d-4b62-92f1-4198f697f3d3');
if (response.statusCode == 200) {
var datas;
datas = jsonDecode(response.body);
final prospectListFromJson = ProspectList.fromJson(datas);
return prospectListFromJson;
} else {
return null;
}
}
FutureBuilder(
future: _fetchData(),builder: (BuildContext context,AsyncSnapshot<ProspectList> snapshot){
if(snapshot.hasData){
prospectList = snapshot.data;
if(prospectList != null){
return List.separated...
}
else{
// Show some error message...
}
}
else if(snapshot.hasError){
// Show some error message...
}
return CircularProgressIndicator();
}
)
如果您使用 FutureBuilder,您就不必怀疑数据是否已加载。