【发布时间】:2019-06-17 02:33:34
【问题描述】:
Dart/Flutter 的新手在从 JSON 响应中分配布尔值时遇到问题 - bool error 是 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,中的:是问题中的错误? -
已经试过了 - 我仍然得到空值......
-
然后在
bool error = body["error"];设置断点并调查body -
哦,我的我的....看起来我在花了 7 个小时的代码后需要喝咖啡休息一下 :) 问题是一个冒号 im json 代码....谢谢你,Gunter 指出这一点出来:)
-
@Matt,请将答案发布为答案而不是评论,然后接受它(是的,您可以接受自己的答案,这是鼓励的),这样问题就不会因为未回答而挂起。跨度>