简体   繁体   中英

Dart / Flutter - cannot assign bool value from JSON response

Newbie to Dart/Flutter here struggling with problem while assigning bool valuse from JSON response - bool error is null and I'm getting:

Failed assertion: boolean expression must not be null

I don't know what's going on as the response is decoded properly and there's no problem with other fields (please take look at Logcat output).

this is my JSON:

{
"error:":false,
"id":1,
"name":"test"
}

my Future:

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");
}

and the Logcat output:

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

Can you please let me know what I am doing wrong here? Any help will be much appreciated! THANK YOU :)

I'd like to thank Günter Zöchbauer for pointing out my silly mistake in JSON structure:

"error:":false

should be:

"error":false

don't forget to take a break from coding guys... ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM