List 在列表中创建列表的第一个元素-颤振、省道
我在一个列表中有一个列表,两个自定义列表 班级价目表List 在列表中创建列表的第一个元素-颤振、省道,list,class,flutter,dart,List,Class,Flutter,Dart,我在一个列表中有一个列表,两个自定义列表 班级价目表 addCategoryWithParameters(String givenCategoryName) { categoriesList.add(Categories(name: givenCategoryName)); } 添加一个新的pricelist非常简单,但是为了添加一个新的categoriesList,我在pricelist类中创建了这个方法 addCategoryWithParameters(String g
addCategoryWithParameters(String givenCategoryName) {
categoriesList.add(Categories(name: givenCategoryName));
}
添加一个新的pricelist非常简单,但是为了添加一个新的categoriesList,我在pricelist类中创建了这个方法
addCategoryWithParameters(String givenCategoryName) {
categoriesList.add(Categories(name: givenCategoryName));
}
调用此方法实际上非常简单,只需Pricelist[i].addCategoryWithParameters(“任意我想要的”)
直到这里,事实上一切都很好
我的问题是在列表为空时添加新的分类列表
我用一个已经包含元素的categoriesList进行了尝试,它总是很好地工作,但是对于一个空列表,它只是返回了一个错误
我还可以使用什么来将第一个元素添加到列表中的列表中,而不是add()
谢谢你的帮助 List categoriesList={Categories(名称:'some name'};
List<Categories> categoriesList = {Categories(name: 'some Name'};
我希望这能有所帮助:)解决方案是您需要在同一个类中初始化和管理单个对象数据,这将消除很多混乱使用空白分类列表初始化价目表。并在Pricelist addCategories中使用方法添加类别
void main() {
List<Pricelist> pList = [];
pList.add(Pricelist(example: 'Example',categoriesList: [])); //initialize
Pricelist[0] with empty categoriesList
print(pList[0].categoriesList.toString());
pList[0].addCategories('My new cat'); //add categoriesList in Pricelist[0]
print(pList[0].categoriesList.toString());
}
class Pricelist{
String example;
List<Categories> categoriesList = [];
Pricelist({this.example, this.categoriesList});
void addCategories(String _categories){
categoriesList.add(Categories(name:_categories));
}
}
class Categories{
String name;
Categories({this.name});
}
void main(){
列表pList=[];
add(Pricelist(例如:'example',categoriesList:[]);//初始化
分类列表为空的价目表[0]
打印(pList[0].categoriesList.toString());
pList[0]。addCategories(“我的新猫”);//在价格表[0]中添加categoriesList
打印(pList[0].categoriesList.toString());
}
班级价目表{
字符串示例;
列表分类列表=[];
Pricelist({this.example,this.categoriesList});
void addCategories(字符串_类别){
添加(类别(名称:_Categories));
}
}
类别{
字符串名;
类别({this.name});
}
void main() {
List<Pricelist> pList = [];
pList.add(Pricelist(example: 'Example',categoriesList: [])); //initialize
Pricelist[0] with empty categoriesList
print(pList[0].categoriesList.toString());
pList[0].addCategories('My new cat'); //add categoriesList in Pricelist[0]
print(pList[0].categoriesList.toString());
}
class Pricelist{
String example;
List<Categories> categoriesList = [];
Pricelist({this.example, this.categoriesList});
void addCategories(String _categories){
categoriesList.add(Categories(name:_categories));
}
}
class Categories{
String name;
Categories({this.name});
}