Search code examples
arrayslistdartindexingaddition

How do I add items of multiple arrays with respect to their indexes in dart?


CODE:

  void func({String value}) async {
   
      final QuerySnapshot snapshot = await _firestore
          .collection('users')
          .where("id", isEqualTo: signedInUser.id)
          .get();

      snapshot.docs.forEach((element) {
        List<dynamic> arr = element.data()["array"];

        print(arr);

        }
}

OUTPUT:

I/flutter (27759): [10, 20, 30, 33, 34, 24]
I/flutter (27759): [2, 42, 45, 23, 85, 51]
I/flutter (27759): [32, 53, 12, 67, 34, 23]

This is what I get when I print the list from Firebase document.

How do I add items of the arrays for each respective indexes? Like; 10 + 2 + 32 for index 0


Solution

  • You should be able to get the List of Lists and then using a for loop sum the data like:

    var lists = snapshot.docs.map((e) => e.data()['array']);
    var sums = <int>[];
    for (int i = 0; i < lists.first.length; i++) {
      var sum = 0;
      for (var list in lists) {
         sum += list[i];
      }
      sums.add(sum);
    }
    

    Be aware that this code is not tested, and you need to make sure that the lists are of equal length or the code might not work as you expect/throw an exception.