A collection of
A collection is a collection of independent data items that have common characteristics, so instead of dealing with each individual item individually, we can use the same calling code to process all the elements of a collection. Collections can be empty and can contain many elements. Collections can have different structures and implementations depending on the purpose. Common types of collections for DART:
- List: Reads elements by index
- Set: Contains elements that can occur only once
- Map: Reads elements using keys
Can the iteration可迭代
Iterable is a collection of elements that can be accessed in order. Iterable in Dart is abstract and cannot be instantiated. But you can create Iterable from lists and sets.
可迭代<int> iterable = [1.2.3];
print(iterable.toSet()); / / {1, 2, 3}
print(iterable.toList()); / / [1, 2, 3]
Copy the code
Iterable differs from List in that Iterable does not have the [] operator to read elements of a particular index as follows:
var value = iterable[0]; // The [] operator does not exist
Copy the code
Instead, you can use the read element elementAt(), which iterates through the elements of the iterable until you reach that position.
可迭代<String> iterable = ['Salad'.'Popcorn'.'Toast'];
String value = iterable.elementAt(0)
print(value) // 'Salad'
Copy the code
for-in
Traverse elements
可迭代<String> iterable = ['Salad'.'Popcorn'.'Toast'];
for (var element in iterable) {
print(element);
}
Copy the code
The first and last
Access to the elements
In some scenarios, you want to access only the first or last element of Iterable. With the Iterable class, elements cannot be accessed directly, so Iterable[0] cannot be called to access the first element. You can access the first element with first and the last element with last. Tip: Accessing the last element of Iterable requires iterating through all the other elements, so last can be slow. Using first or last on an empty Iterable causes a StateError exception.
可迭代<String> iterable = const ['Salad'.'Popcorn'.'Toast'];
print('The first element is ${iterable.first}');
print('The last element is ${iterable.last}');
Copy the code
firstWhere()
Use firstWhere() to find the first element that satisfies a particular condition. This method requires that you pass in a function that returns the first element that matches if the input meets a condition. If firstWhere is not found and the orElse argument is ignored, a StateError exception is thrown.
bool predicate(String item) {
return item.length > 5;
}
void main() {
const items = ['Salad'.'Popcorn'.'Toast'.'Lasagne'];
var foundItem1 = items.firstWhere((item) => item.length > 5);
print(foundItem1);
var foundItem2 = items.firstWhere(predicate);
print(foundItem2);
///If no value is found, the 'orrelse' function can also be used
var foundItem3 = items.firstWhere(
(item) => item.length > 10,
orElse: () => 'None! ',);print(foundItem3);
}
Copy the code
singleWhere()
Gets an element from an Iterable object that satisfies the condition, but it expects only one element to satisfy the condition. If more than one or none of the elements satisfy the condition, StateError is thrown. Same usage as firstWhere. Tip: singleWhere() steps through the Iterable object until the last element, which may cause an exception if the Iterable is infinite or contains a large number of elements.
可迭代<int> iterable = [8.12.4.1.17.33.10];
int a = iterable.singleWhere((e) => e > 30);
int b = iterable.singleWhere((e) => e > 10);
int c = iterable.singleWhere((e) => e > 10, orElse: () => - 1);
int d = iterable.singleWhere((e) => e > 40, orElse: () => - 1);
print(a); / / 33
print(b); / / an error
print(c); / / an error
print(d); // -1
Copy the code
where()
If you want to find all elements that satisfy a condition, you can do so using the where() method.
var evenNumbers = const [1.2 -.3.42].where((number) => number.isEven);
print(evenNumbers); // [-2, 42]
for (var number in evenNumbers) {
print('$number is even.');
}
if (evenNumbers.any((number) => number.isNegative)) {
print('evenNumbers contains negative numbers.');
}
// If no element satisfies the function, the output is null.
var largeNumbers = evenNumbers.where((number) => number > 1000);
if (largeNumbers.isEmpty) {
print('largeNumbers is empty! ');
}
Copy the code
takeWhile()
TakeWhile retrieves all of the elements that satisfy the condition from the Iterable object until they do not, and returns the set of elements that satisfy the condition until they do not. If no element satisfies the function in where(), the method returns an empty Iterable. Unlike singleWhere() or firstWhere(), where() does not throw StateError
const numbers = [1.3.2 -.0.4.5];
varnumbersUntilZero = numbers.takeWhile((number) => number ! =0);
print('Numbers until 0: $numbersUntilZero'); // Numbers until 0: (1, 3, -2)
print(numbersUntilZero.toList()); // [1, 3, -2]
Copy the code
skipWhile()
The skipWhile skips all elements that meet the criteria from the Iterable object until they do, breaking out of the iteration and returning the remaining set of elements that do not meet the criteria.
varnumbersStartingAtZero = numbers.skipWhile((number) => number ! =0);
print('Numbers starting at 0: $numbersStartingAtZero'); // Numbers starting at 0: (0, 4, 5)
Copy the code
Condition check
With Iterable, it is sometimes necessary to verify that the elements in the collection meet certain conditions without using for-in. \
every()
Dart provides the every method: to determine if all elements meet a condition.
可迭代<int> iterable = {- 1.0.1.2};
bool satisfy = iterable.every((item)=> item > 2); // Whether all elements satisfy >2
print(satisfy) // false
Copy the code
any()
Dart provides the any method: to determine if at least one element satisfies a condition.
Iterable < int > Iterable = {1, 2}; // If at least one element satisfies >=2 bool satisfy = iterable. Any ((item)=> item >=2); // trueCopy the code
map()
The Iterable object can use the map method to manipulate or replace each element in the collection, eventually returning a new collection.
var numbersByTwo = const [1.2 -.3.42].map((number) => number * 2);
print('Numbers: $numbersByTwo'); // Numbers: (2, -4, 6, 84)
Copy the code