1

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.