flutter - 在 Flutter 应用程序中处理 JSON 解析中的空值
问题描述
我正在从数据库中获取详细信息,然后解析 json 值。下面是http请求的代码。
Future <List> getData() async{
if(endofrecord == false){
try{
var body = { "uid" : dtguid, "deviceid": deviceid, "offset": offset};
var url = 'http://192.168.1.100:8080/get_recommended.php';
// Starting Web API Call.
var response = await http.post(url, body: json.encode(body)).timeout(Duration(seconds: 5),
onTimeout: (){
// throw Exception();
_showSnackBar(context,'Some issue with connectivity. Can not reached to server.',Colors.redAccent);
//or you can also
return null;
});
if(response.statusCode == 200){
final data = parsedataFromJson(response.body);
setState(() {
recommended = true;
_inProcess = false;
if(data.count == null){
count = 0;
}else{
offset = offset + 5;
print(offset);
count = data.count;
}
if(data.content.length > 0 && data.content[0].name != 'Empty'){
for (var i in data.content) {
lists.add(i);
}
}else{
nodata = 'No Record Found';
endofrecord = true;
_showSnackBar(context,nodata,Colors.redAccent);
}
});
print(lists.length);
}
}catch(e){
print("Exception Caught: $e");
_showSnackBar(context,'Some issue with connectivity. Could not connect to server.',Colors.redAccent);
}
return lists;
}else{
return null;
}
}
这是JSON解析。
import 'dart:convert';
DatabyPrice databyPriceFromJson(String str) => DatabyPrice.fromJson(json.decode(str));
class DatabyPrice {
DatabyPrice({
this.count,
this.content,
this.success,
});
int count;
List<Content> content;
bool success;
factory DatabyPrice.fromJson(Map<String, dynamic> json) => DatabyPrice(
count: json["count"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
success: json["success"],
);
}
class Content {
Content({
this.name,
this.uid,
this.pic,
this.state,
this.country,
this.lastLogin,
this.tabout,
this.averageOrating,
this.pricing,
});
String name;
int uid;
String pic;
String state;
String country;
String tabout;
String lastLogin;
String averageOrating;
List<Pricing> pricing;
factory Content.fromJson(Map<String, dynamic> json) => Content(
name: json == null ? 'Empty' : json["name"],
uid: json == null ? 0 :json["uid"],
pic: json == null ? 'Empty' :json["pic"],
state: json == null ? 'Empty' :json["state"],
tabout: json == null ? 'Empty' :json["tabout"],
country: json == null ? 'Empty' :json["country"],
lastLogin: json == null ? 'Empty' : json["last_login"],
averageOrating: json == null ? '0' :json["average_orating"],
pricing: List<Pricing>.from(json["pricing"].map((x) => Pricing.fromJson(x))),
);
}
class Pricing {
Pricing({
this.uid,
this.price,
this.serviceType,
});
int uid;
int price;
String serviceType;
factory Pricing.fromJson(Map<String, dynamic> json) => Pricing(
uid: json == null ? 0 :json["uid"],
price: json == null ? 0 :json["price"],
serviceType: json == null ? 'Empty' :json["service_type"],
);
}
当有一些记录从数据库返回时,上面的代码工作正常,但如果没有数据或记录结束,则它不起作用。我得到以下错误。
I/flutter ( 5255): Receiver: null
I/flutter ( 5255): Tried calling: []("pricing")
I/flutter ( 5255): Exception Caught: NoSuchMethodError: The method '[]' was called on null.
当http请求没有返回数据时,我该如何处理这种情况?
解决方案
要将 JSON 转换为 PODO,您必须使用 JSON to Dart之类的东西
生成模型后,您可以轻松检查来自后端的空元素。
推荐阅读
- java - 当关闭挂钩或终结器未完成时会发生什么?
- apache-spark - monotonically_increasing_id 大于数据框中的总记录
- html - 如何在 Angular 8 中自定义选择框?
- java - 调用最终类的静态方法时如何PowerMockito.doNothing?
- ios - Do 和 Map 有什么区别?
- ruby - Ruby unix 套接字客户端和服务器示例
- c - realloc():将项目附加到数组时下一个大小无效
- python - 如何在不保存或使用 ORM 的情况下上传多个 csv
- c# - 如何在 C# 中从数据库中检索 KeyValuePair 的值?
- android-studio - 如何在 Android Studio 的 gradle build 中启用 --stacktrace 或 --info 或 --debug 或 --scan 选项?