-2

Does anyone here know/have references/examples of how to add up the values in the list in Flutter. Thanks

enter image description here

sharon
  • 363
  • 2
  • 11
  • Does this answer your question? [What is the cleanest way to get the sum of numbers in a collection/list in Dart?](https://stackoverflow.com/questions/10405348/what-is-the-cleanest-way-to-get-the-sum-of-numbers-in-a-collection-list-in-dart) – Xuuan Thuc Dec 27 '22 at 02:27

2 Answers2

1

use sum:

import 'package:collection/collection.dart';

void main() {
  final list = [1, 2, 3, 4];
  final sum = list.sum;
  print(sum); // prints 10
}

Your question is similar to the question here, refer to it for more information

Xuuan Thuc
  • 2,340
  • 1
  • 5
  • 22
0

you can use .fold() method

  • fold method:
T fold<T>(T initialValue, T Function(T, Data) combine)

example for sum list of object:

void main() {
  List<Data> listData = [
    Data(count: 10, name: 'a'),
    Data(count: 12, name: 'bc'),
    Data(count: 21, name: 'abc'),
  ];

  int sum = listData.fold(0, (int preValue, data) => preValue + data.count);

  print(sum);// 43
}

class Data {
  int count;
  String name;
  Data({required this.count, required this.name});
}

pmatatias
  • 3,491
  • 3
  • 10
  • 30