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
Array to list:
because .map return iterable.
var fruits = ['banana', 'pineapple', 'orange', 'watermelon', 'apple']; var fiboNumbers = [1, 2, 3, 5, 8, 13, 21]; List
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 );