我有一个 Expanded 小部件,在这个小部件中,我创建了新的成分对象,然后我希望它添加另一个接受成分对象的类的列表,但是当我尝试使用列表的添加功能时,我遇到了错误如下。
Expanded(
flex: 40,
child: ListView.builder(
shrinkWrap: true,
itemCount: items.length,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.all(2.0),
child: GestureDetector(
onTap: ()async{
if(_ingredients.length==0){
Ingredient ingredient= Ingredient(ingredientName:"${items[index]}",dropDownValue: "Çay Kaşığı",ingredientAmount:null);
categoryModels[widget.subCategoryId].subCategoryModels[widget.subCategoryCardId].ingredients.add(ingredient);
addIngredient(ingredient,context);
_toggleCardHeight();
_toggleCardSize();
setState(() {
});
}
else{
var flag=0;
for(var i in _ingredients){
if(i.ingredientName==items[index]){
flag=-1;
var response= await showAlertDialog(context);
if (response==false){
setState(() {});
}
}
}
if(flag==0){
Ingredient ingredient=Ingredient(ingredientName:"${items[index]}",dropDownValue: "Çay Kaşığı",ingredientAmount: null);
categoryModels[widget.subCategoryId].subCategoryModels[widget.subCategoryCardId].ingredients.add(ingredient);
addIngredient(ingredient,context);
setState(() {});
}
}
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(90),
border: Border.all(style:BorderStyle.solid,width: 1),
color: Colors.white54,
),
child: Padding(
padding: EdgeInsets.all(5),
child: Text('${items[index]}',style: TextStyle(fontWeight: FontWeight.bold),)),
),
),
);
},
),
),
这里是我想将成分作为对象添加到列表中的类。
class CategoryModel{
CategoryModel(
{
this.categoryId,
this.categoryImagePath,
this.categoryName,
this.categoryColor,
this.subCategory
});
final SubCategoryModel subCategory;
final Color categoryColor;
final List<SubCategoryModel> subCategoryModels=[SubCategoryModel()];
int categoryId;
String categoryImagePath;
String categoryName;
}
class SubCategoryModel{
SubCategoryModel(
{
this.subCategoryId,
this.subCategoryImagePath,
this.subCategoryName,
this.categoryColor,
this.recipeId,
this.ingredients,
this.recipePhotoDir,
this.recipeTextFromSpeechProcessing,
this.recordedVoiceDir});
final Color categoryColor;
final double recipeId;
int subCategoryId;
String subCategoryImagePath;
String subCategoryName;
List<Ingredient> ingredients= [];
String recipeTextFromSpeechProcessing;
String recipePhotoDir;
String recordedVoiceDir;
}
E/flutter ( 7266): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'add' was called on null.
E/flutter ( 7266): Receiver: null
E/flutter ( 7266): Tried calling: add(Instance of 'Ingredient')
有人可以帮我吗?我该如何处理这个问题。