在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到Dart

一旦生成了模型,就可以很容易地检查来自后端的null元素。

您在try{} catch{}块中发现任何错误了吗。如果您没有遇到错误,请检查您的自定义JSON转换器。尝试在没有自定义JSON解析器的情况下进行测试,并使用将JSON转换为Map的普通转换器dart:async模块,类似于这个import dart:asyncdart。如果它没有改变任何东西,请尝试使用.then().catch()语法。如果没有尝试检查后端数据库,它们可能是错误的

最新更新