Home > Software engineering >  for loop get only last index not correct index flutter
for loop get only last index not correct index flutter

Time:11-22

I have one list and this list format is month wise data I'm putting month wise data in list but only show the last index data not proper data, If I print data inside if condition is print perfect but inside widget not shown correct. I'm adding some code:

Declarations:

int monthIndex, 
List transactionLists =[];

my method:

myMethod(){
    for (var i = 1; i < transactionLists.length; i  ) {
      if (monthName[monthIndex] == "July") {
        data=transactionLists[i].july.toString();
         print(data);
      } else if (monthName[monthIndex] == "August") {
        data = transactionLists[i].august.toString();
      } else if (monthName[monthIndex] == "September") {
        data = transactionLists[i].september.toString();
      } else if (monthName[monthIndex] == "October") {
        data = transactionLists[i].october.toString();
      } //.... up to all 12 months
     }
     return ListView.builder(
      padding: EdgeInsets.zero,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: transactionLists.length,
      itemBuilder: (context, childIndex) {
         return Text(
            data,
           );
      }
}

what I have try data[childIndex]

Output - 1245,1245,1245 for all index get same value I want correct value with like 5445,8545,1245 it comes from the list

CodePudding user response:

You are using data in a for loop which constantly update it, that cause your problem. First you need define data as list like this:

List data = [];

then use it like this:

myMethod(){
    for (var i = 0; i < transactionLists.length; i  ) {
      if (monthName[monthIndex] == "July") {
        data.add(transactionLists[i].july.toString());//<--- change this
         print(data);
      } else if (monthName[monthIndex] == "August") {
        data.add(transactionLists[i].august.toString());//<--- change this
      } else if (monthName[monthIndex] == "September") {
        data.add(transactionLists[i].september.toString());//<--- change this
      } else if (monthName[monthIndex] == "October") {
        data.add(transactionLists[i].october.toString());//<--- change this
      } //.... up to all 12 months
     }
     return ListView.builder(
      padding: EdgeInsets.zero,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: data.length,//<--- change this
      itemBuilder: (context, childIndex) {
         return Text(
            data[childIndex],//<--- change this
           );
      }
}
  • Related