首页 > 解决方案 > NoSuchMethodError (NoSuchMethodError: 方法 'add' 在 null 上被调用

问题描述

我想用 JSON 文件中的一些数据填充 Flutter 中的列表。但是,我的代码不断抛出异常"NoSuchMethodError (NoSuchMethodError: The method 'add' was called on null."

我的错误在哪里?

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,
}

我的代码:

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

标签: flutterdart

解决方案


你需要先初始化列表

改变

List<String> materialAmountList;

List<String> materialAmountList = new List();

推荐阅读