Check if key exists in multidimensional json response [Flutter] [Dart]

1,486

Looks like sometimes your decodedResponse value is null. You should check like this:

if(decodedResponse != null && decodedResponse['ingredients'] != null && decodedResponse['ingredients']['additives'] != null){}

Like this you will check always if it has a value because it seams like your response from the API sometimes gives you null.

Share:
1,486
trrrnncy
Author by

trrrnncy

Updated on December 12, 2022

Comments

  • trrrnncy
    trrrnncy over 1 year

    I'm reading some json data from an http endpoint and continue to work with the result like this:

    var decodedResponse = json.decode(response.body);
    if(decodedResponse['ingredients']['additives'] != null) {
      getAdditiveList = await getAdditiveNames(decodedResponse['ingredients']['additives']);
      decodedResponse['ingredients']['additives'] = getAdditiveList;
    }
    

    Since sometimes the 'additives' or even the 'ingredients' key is not part of the json response, I get the following error:

    [VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
    Receiver: null
    Tried calling: []("additives")
    

    I think the following would technically work as a validation, but it doesn't look like a good idea:

    if(decodedResponse.containsKey("ingredients")){
        if(decodedResponse['ingredients'].containsKey("additives")){
        }
    }
    

    Any help would be appreciated! Thanks!