Home > Software design >  Flutter how to get total items in all lists
Flutter how to get total items in all lists

Time:12-30

I got this list in flutter:

List<dynamic> days = [];

Printing it gives me this result:

[[1, 3, 4, 6], [1, 2, 3]]

Now I want to get total items in this list. What is the best way to do that?

I have tried this but it doesn't work:

print(days.sum);

I want to get the total items from all lists. (1,3,4,6 1,2,3)= total:7items.

Is that possible?

CodePudding user response:

try this

    List<dynamic> days = [[1, 3, 4, 6], [1, 2, 3]];
int length = 0 ;
for (var item in days ){
length = length   int.parse ('${ item.length ?? 0}');
} 
print ('Total Length : $length  ');

CodePudding user response:

Considering that you are using List<dynamic> as the type of days you can write

print(days.whereType<List>().flattened.length);

If days was declared as List<List> to begin with like

List<List> days = [];

you can shorten it to

print(days.flattened.length);

flattened is part of the collection package so you would need to add that and import it like:

import 'package:collection/collection.dart';

If you do not wish to use that package you could copy the implementation of it yourself and add it to your code:

/// Extensions on iterables whose elements are also iterables.
extension IterableIterableExtension<T> on Iterable<Iterable<T>> {
  /// The sequential elements of each iterable in this iterable.
  ///
  /// Iterates the elements of this iterable.
  /// For each one, which is itself an iterable,
  /// all the elements of that are emitted
  /// on the returned iterable, before moving on to the next element.
  Iterable<T> get flattened sync* {
    for (var elements in this) {
      yield* elements;
    }
  }
}

CodePudding user response:

You can try to use fold method.

List<dynamic> days = [1, 2, 3, 4 , 6];
  
  var sumDays = days.fold<dynamic>(0, (prev, element) => prev   element);
  
  print(sumDays);

in print it returns 16.

CodePudding user response:

void main() {
  List<dynamic> list = [1, 2, [3, 4, [5, 6]], 7, 8];
  int count = countElements(list);
  print(count); 
}    

int countElements(List<dynamic> list) {
  int count = 0;
  for (var element in list) {
    if (element is List) {
      count  = countElements(element);
    } else {
      count  ;
    }
  }
  return count;
}

Here is a recursive function. This example prints "8".

  • Related