skip to Main Content

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

enter image description here

2

Answers


  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

    Login or Signup to reply.
  2. 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});
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search