【问题标题】:Dart / Flutter - cannot assign bool value from JSON responseDart / Flutter - 无法从 JSON 响应中分配 bool 值
【发布时间】:2019-06-17 02:33:34
【问题描述】:

Dart/Flutter 的新手在从 JSON 响应中分配布尔值时遇到问题 - bool errornull,我得到了:

断言失败:布尔表达式不能为空

我不知道发生了什么,因为响应已正确解码并且其他字段没有问题(请查看 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,请将答案发布为答案而不是评论,然后接受它(是的,您可以接受自己的答案,这是鼓励的),这样问题就不会因为未回答而挂起。跨度>

标签: json dart flutter boolean


【解决方案1】:

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

"error:":false

应该是:

"error":false

别忘了从编码人员那里休息一下...... ;)

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2020-10-31
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多