Dart / Flutter - 无法从JSON响应中分配布尔值

6

作为一名Dart/Flutter的新手,我在从JSON响应中分配布尔值时遇到了问题 - bool errornull,我得到了以下错误信息:

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

请问我在这里做错了什么?非常感谢您的帮助!谢谢 :)

4
请尝试使用bool error = body["error:"];,或者是在"error:":false,中的:是问题中的错误吗? - Günter Zöchbauer
已经尝试过了 - 我仍然得到空值... - Matt
然后在 bool error = body["error"]; 处设置一个断点,并调查 body - Günter Zöchbauer
哦,天啊……看起来我需要喝杯咖啡了,在代码里花了七个小时 :) 问题在json代码中有一个冒号…… 非常感谢您指出这一点,Gunter :) - Matt
@Matt,请将答案发布为答案而非评论,然后接受它(是的,您可以接受自己的答案,并且这是鼓励的),以使问题不会悬而未决。 - Ski
1个回答

6

我要感谢Günter Zöchbauer指出了我的JSON结构中的愚蠢错误:

"error:":false

should be:

"error":false

各位程序员,别忘了休息一下哦... ;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接