Salatgurke
Salatgurke

Reputation: 2184

NoSuchMethodError (NoSuchMethodError: The method 'add' was called on null

I am rying to fill a List in Flutter with some data from a JSON file. However, my code keeps throwing the exception "NoSuchMethodError (NoSuchMethodError: The method 'add' was called on null."

Where is my mistake?

JSON:

 {
    "#1": "6",
    "#2": null,
    "#3": null,
    "#4": null,
    "#5": null,
    "#6": null,
    
    "material_1": "stone",
    "material_2": null,
    "material_3": null,
    "material_4": null,
    "material_5": null,
    "material_6": null,
}

My Code:

List<String>getMaterialAmounts(){
    List<String> materialAmountList;
    for(int i = 0;i<6;i++){
      materialAmountList.add(_json["#${i+1}"] ?? "-1");
    }
    return materialAmountList;
  }

Upvotes: 1

Views: 437

Answers (1)

VertexGames
VertexGames

Reputation: 97

you need to initialize the list first

Change

List<String> materialAmountList;

To

List<String> materialAmountList = new List();

Upvotes: 1

Related Questions