Home > Software engineering >  I want to get sum array of list
I want to get sum array of list

Time:07-20

String getTotalPayment({ List<List<double?>>? totalPrice}) {
totalPrice = [[132], [143], [110]];
if (totalPrice.isEmpty) {
  return "0";
} else {
  double sum = 0;
  for (var i = 0; i < totalPrice.length; i  ) {
    sum  = totalPrice[i] as double;
  }
  // totalPrice.reduce((value, current) => value   current);
  return sum.toString();
}


 }

I get this error:

type 'List<double?>' is not a subtype of type 'double' in type cast!! 
uTotalPayment: pending.data !=null ?
                        getTotalPayment(totalPrice: pending.data!.map((e) => e.invoices!.map((e) => e.total!.toDouble()).toList()

CodePudding user response:

Try to loop it again to get the data inside on each data on the list

  List<List<double?>> totalPrice = [[132], [143], [110]];
  double sum = 0;
  for(var x in totalPrice){
      for(var y in x){
          sum  = y!;
      }
  }
  print(sum.toString()); // Result 385

you can also use fold answered by @Kaushik Chandru

CodePudding user response:

Since you have a list of list. You may have to use a nested loop to get the sum. You can give this a try

double sum = totalPrice.fold(0, (a,b) => (a.fold(0, (c,d) => c d))   (b.fold(0, (e,f)=>e f)));
print(sum);

CodePudding user response:

try this

String getTotalPayment({ List<List<double?>>? totalPrice}) {
totalPrice = [[132], [143], [110]];
if (totalPrice.isEmpty) {
  return "0";
} else {
  double sum = 0;
  for(var x in totalPrice){
      for(var y in x){
          sum  = y!;
      }
  }
  // totalPrice.reduce((value, current) => value   current);
  return sum.toString();
}
  • Related