1
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()
Ken White
  • 123,280
  • 14
  • 225
  • 444
Chhily Lim
  • 104
  • 7

4 Answers4

2

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

Arbiter Chil
  • 1,061
  • 1
  • 6
  • 9
1

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);
Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
1

Use standard collection functions:

final sum = items
  .expand((element) => element) // Flattern list
  .whereType<double>() // Remove null elements
  .fold<double>(0.0, (previousValue, element) => previousValue + element); // Sum of
Wilson Tran
  • 4,050
  • 3
  • 22
  • 31
  • I have tried this too, but a bit complex to understand – Chhily Lim Jul 20 '22 at 07:10
  • @ChhilyLim This is a common approach in modern programming languages. In my answer, I have referenced from https://stackoverflow.com/questions/15413248/how-to-flatten-a-list and https://stackoverflow.com/questions/10405348/what-is-the-cleanest-way-to-get-the-sum-of-numbers-in-a-collection-list-in-dart – Wilson Tran Jul 20 '22 at 07:25
-2

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();
}
Nikunj Ramani
  • 324
  • 1
  • 8