Reputation: 1272
i want to create 4 new lists from a single list. i created this, in this if i do some changes in a single list it changed to all of them. i want to manipulate each list individually.
List<DietModel> foodList = [];
List<DietModel> breakFastList = [];
List<DietModel> lunchList = [];
List<DietModel> snacksList = [];
List<DietModel> dinnerList = [];
void getFoodList() async {
foodList = await _dietPageRepositoryImpl.getAll();
breakFastList = foodList;
lunchList = foodList;
snacksList = foodList;
dinnerList = foodList;
}
Upvotes: 1
Views: 58
Reputation: 199
By using breakFastList = foodList;
you set breakFastList to be foodList, meaning that if foodList changes, breakFastList will also change.
By using breakFastList.addAll(foodList);
you will add each item that exists in foodList to breakFastList individually. Meaning that if you delete an item from foodList, or add an item to foodList afterwards, breakFastList will remain the same.
Upvotes: 1
Reputation: 2439
First you have to initialize your list like you did
List<DietModel> foodList;
List<DietModel> breakFastList;
List<DietModel> lunchList;
List<DietModel> snacksList ;
List<DietModel> dinnerList;
and then on the flutter initState
you have to tell that they are a type of list.
@override
void initState() {
super.initState();
foodList = List();
breakFastList = List();
lunchList = List();
snacksList = List();
dinnerList = List();
}
and in the end when you fetch your data you can copy your list data to other 4 lists with this.
void getFoodList() async {
foodList = await _dietPageRepositoryImpl.getAll();
breakFastList = List.from(foodList);
lunchList = List.from(foodList);
snacksList = List.from(foodList);
dinnerList = List.from(foodList);
}
Upvotes: 1
Reputation: 2678
Use List.from(mynewlist)
instead of mylist = mynewlist
If anyone knows a workaround for classes - that would be interesting!
Upvotes: 1