Home > front end >  The previous data in listoflistdata gets replaced by second index data when i add data to listoflist
The previous data in listoflistdata gets replaced by second index data when i add data to listoflist

Time:04-23

I created List of List of Objects i.e. (List<List> ListofListData )then another List i.e.( List mealslist) ,Now i get list of data from Api Then i want to add meals to mealslist and Finally the meal list to ListofListData... I ran the loop and added data and works fine for first index data but when i add list of meals for second index to listoflistData.. The previous data in listoflistdata gets replaced by second index data Api data Api Resonse My code .....

    List<TourMealsModel?> tourmealslist = [];
    List<TourMealsModel?> tourmealslistinitial = [];
    List<List<TourMealsModel?>> tourmealslistday = [];
    for (var i = 0;i < widget.tours.tourDaysPlannings!.length;i  ) {
    mealstobeadded.clear();
    tourmealslistinitial.clear();
    for (var j = 0;j <widget.tours.tourDaysPlannings![i].meals!.length;j  ) {
    var mealsId = widget.tours.tourDaysPlannings![i].meals![j].meal!.id;
    final index = tourmealslistindexWhere((element) => element!.id == mealsId);
    if (index >= 0) {tourmealslistinitial.add(tourmealslist[index]);  }                           
    }
    tourmealslistday.add(tourmealslistinitial);
    }
    class TourMealsModel {
    int? id;
    String? meal;
    String? icon;
    String? description;
    bool isselected = false;
    TourMealsModel(
    {this.id,
    this.meal,
    this.icon,
    this.description,
    this.isselected = false});}
  

CodePudding user response:

you keep reusing the same tourmealslistinitial for each index. When you do tourmealslistinitial.clear(); you clear it also for the previous indexes because they have the same reference to the same list. What you probably need to do is instead of

tourmealslistinitial.clear();

do

tourmealslistinitial = [];

So each index will have a new separate list

  • Related