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... ;)

Share:
3,657
Matt
Author by

Matt

Updated on December 09, 2022

Comments

  • Matt
    Matt over 1 year

    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 :)

    • Günter Zöchbauer
      Günter Zöchbauer over 5 years
      Try bool error = body["error:"]; or is the : in "error:":false, a mistake in the question?
    • Matt
      Matt over 5 years
      Already tried that - I'm still getting null value...
    • Günter Zöchbauer
      Günter Zöchbauer over 5 years
      Then set a breakpoint at bool error = body["error"]; and investigate body
    • Matt
      Matt over 5 years
      Oh 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
      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.