我是 FLutter 新手,尝试获取一些 JSON 数据并将其显示在列表中。当我尝试连接到 API 时,它工作得很好,并且我从服务器获得了 JSON 响应。但是当我尝试使用 FutureBuilder 在列表中显示它时,它说快照返回 null,即使认为来自数据的响应是存在的。 这是我从服务器得到的 JSON 响应
{
"error_code" : "00",
"error_message" : "Success",
"user_list" :
[
{
"name" : "Swift",
"user_id": "2048"
}, {
"name" : "Python",
"user_id": "1024"
}, {
"name" : "Objective-C",
"user_id": "512"
}, {
"name" : "Ruby",
"user_id": "256"
}
]
}
这是我的 get 方法,因为我只想使用 user_list
字段,我尝试以这种方式对其进行过滤。
Future<List<Patient>> getPatient() async {
final response = await http.get(Uri.parse(url+"/interns"));
if (response.statusCode == 200) {
var data = json.decode(response.body);
print(data['user_list']);
return List<Patient>.from(data['user_list'].map((item)=>Patient.fromJson(item)));
} else {
throw Exception("Failed");
}
}
这是抛出错误的 FutureBuilder
FutureBuilder<List<Patient>>(
future: patientService.getPatient(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasError) {
print(snapshot);
return Center(
child: Text("Error"),
);
} else if (snapshot.hasData){
List<Patient> patients = snapshot.data;
return _buildListView(patients);
} else {
return Center(
child: Container(),
);
}
},
),
这是患者模型类
Patient({required this.name, required this.userId});
factory Patient.fromJson(Map<String, dynamic> json) {
return Patient(
name :json['name'],
userId : json['userId']
);
}
这是我的错误
AsyncSnapshot<List<Patient>>(ConnectionState.done, null, Expected a value of type 'String', but got one of type 'Null'
答案 0 :(得分:1)
应该是
json['user_id ']
而不是 json['userId']
。参数名称不同,这就是您收到 Null 错误的原因。
答案 1 :(得分:0)
正如 John 在这篇文章中提到的,要修复您的代码,您需要在解析 user_id
数据时使用 Patient
。
但是,不确定您是否已经在代码中解决了此问题,但您共享的代码最终会对端点进行多次额外调用,因为您正在 Build 方法中创建 Future getPatient
。如果您在代码中放置了断点,则在第一次重新加载应用时应至少调用 3 次。
您应该将 Future 存储在局部变量中并在 FutureBuilder
中引用它。这是我看到人们制作的 very common problem,我过去也遇到过这个问题。