Dart / Flutter - cannot assign bool value from JSON response
3,657
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... ;)
Author by
Matt
Updated on December 09, 2022Comments
-
Matt over 1 year
Newbie to Dart/Flutter here struggling with problem while assigning bool valuse from JSON response -
bool error
isnull
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 :)
-
Günter Zöchbauer over 5 yearsTry
bool error = body["error:"];
or is the:
in"error:":false,
a mistake in the question? -
Matt over 5 yearsAlready tried that - I'm still getting null value...
-
Günter Zöchbauer over 5 yearsThen set a breakpoint at
bool error = body["error"];
and investigatebody
-
Matt over 5 yearsOh my my my .... looks like I need a coffe break after spending 7 hours with code :) The problem was a colon im json code.... THANK YOU, Gunter for pointing this out :)
-
Ski over 5 years@Matt, please post answers as answer not as a comment, and then accept it (yes you can accept your own answer and this is encouraged) so that question doesn't hang as unanswered.
-