[Dart] Manipulate Lists/Arrays in Dart

We will learn how to work with Lists using a variety of methods made available in the dart:core library. We will explore the top methods for working with List type collections.

Learn more about Lists at https://api.dartlang.org/stable/2.2.0/dart-core/List-class.html

 

Array to list:

because .map return iterable.

  var fruits = ['banana', 'pineapple', 'orange', 'watermelon', 'apple'];
  var fiboNumbers = [1, 2, 3, 5, 8, 13, 21];
  List<Map<String, dynamic>> users = [
    { 'name': 'John', 'age': 18 },
    { 'name': 'Jane', 'age': 21 },
    { 'name': 'Mary', 'age': 23 },
  ];

    // array to list
    var mappedFruits = fruits.map((fruit) => 'I love $fruit').toList();
    print(mappedFruits);

 

reduce vs fold:

reduce: doesn't provide the init value, but 'fold' does:

  const initialValue = 10;
  var sum2 = fiboNumbers.fold(initialValue, (curr, next) => curr + next);
  print( sum2 );
  
  var sum = fiboNumbers.reduce((curr, next) => curr + next);
  print( sum );

 

filtering:

  var over21s = users.where((user) => user['age'] > 21);
  print( over21s.length );
  
  var nameJ = users.firstWhere((user) => user['name'].startsWith('J'), orElse: () => null);
  print( nameJ );
  
  var under18 = users.singleWhere((user) => user['age'] < 18, orElse: () => {'error': 'Not Found'});
  print( under18 );

 

take & skip:

  print( fiboNumbers.take(3).toList() );
  print( fiboNumbers.skip(5).toList() );
  print( fiboNumbers.take(3).skip(2).take(1).toList() );

 

expend: the same as flatMap in JS

  var flattened = [[1, 2], [3, 4]].expand((pair) => pair).toList();
  print( flattened );
  
  var duplicated = fiboNumbers.expand((i) => [i, i]).toList();
  print( duplicated );

 

Guess you like

Origin www.cnblogs.com/Answer1215/p/11459398.html