作为一名Dart/Flutter的新手,我在从JSON响应中分配布尔值时遇到了问题 - bool error
是 null
,我得到了以下错误信息:
Failed assertion: boolean expression must not be null
我不知道发生了什么,因为响应已经被正确地解码,其他字段没有问题(请查看Logcat输出)。
这是我的JSON:
{
"error:":false,
"id":1,
"name":"test"
}
我的未来:
Future<dynamic> fetchData() async {
http.Response response = await http.get(Values.URL, headers: {HttpHeaders.contentTypeHeader: "application/json"});
if (response.statusCode == 200) {
debugPrint(response.body);
var body = jsonDecode(response.body);
bool error = body["error"];
var id = body["id"];
var name = body["name"];
print("bool:" + error.toString());
print("id:" + id.toString());
print("name:" + name);
if (error) {
print("no error");
} else {
print("error");
}
} else {
throw Exception("statusCode exception e");
}
和 Logcat 输出:
I/flutter: {
I/flutter: "error:":false,
I/flutter: "id":1,
I/flutter: "name":"test"
I/flutter: }
I/flutter: bool:null
I/flutter: id:1
I/flutter: name:test
I/flutter: Failed assertion: boolean expression must not be null
请问我在这里做错了什么?非常感谢您的帮助!谢谢 :)
bool error = body["error:"];
,或者是在"error:":false,
中的:
是问题中的错误吗? - Günter Zöchbauerbool error = body["error"];
处设置一个断点,并调查body
。 - Günter Zöchbauer