Create a list with a loop in 1 line
You can put a
List myList = [for(int i=0;i<10;i++) i];
print(myList); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Map
In many programming languages, a map is the name of a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called
List myList = [1,2,3,4,5];
List myList2 = myList.map((item){
return item * item;
}).toList();
print(myList2); // [1, 4, 9, 16, 25]
Where
List myList = ['apple','banana','cat','dog','egg','face','good'];
var result = myList.where((item){
return item.contains('o');
});
print(result.toList()); //[dog, good]
Reduce
- accumulate
List myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; int result = myList.reduce((accumulator, currentElement){ return accumulator + currentElement; }); print(result); // 55
- find max
List myList = [2,9,4,6,1,3,9,4,0,2]; int result = myList.reduce((max, currentElement){ return currentElement>max?currentElement:max; }); print(result); // 9
Every
Checks
- every item < 5 ?
List myList = [3,2,1,3,2,3]; bool result = myList.every((item){ return item < 5; }); print(result); //true
Any
Checks
- Is any number less than zero?
List myList = [-1, 0, 1, 2, 3, 4, 5]; bool result = myList.any((item){ return item < 0; }); print(result); // true
for…in
In Dart, the for...in loop takes an expression as an iterator and
List myList = [1, 2, 3, 4, 5];
for(int i in myList){
print(i); //1 2 3 4 5
}
沒有留言:
發佈留言