How to use List and Iterable in Dart?

2022/12/11 15:30

Dart’s List and Iterable are similar, but they also have some differences. A List is an ordered collection that allows you to insert and access elements at a specified index. Iterable, on the other hand, is an unordered collection that cannot access elements at the specified index, but can use for-in statements to traverse its elements.

In Dart, you can use the List.from() method to convert Iterable to List, and then you can use the methods provided by List to access the element. For example:

Iterable words = [“apple”, “banana”, “orange”];

List wordless = List.from(words);

// Print the third word

Print(wordless[2]); // Output: orange

Alternatively, you can use the.where() method to filter Iterable elements, such as only the even number of them:

Iterable numbers = [1, 2, 3, 4, 5, 6];

Iterable evenNumbers = numbers.where((number) → number % 2 == 0);

For (int number in evenNumbers) {

Print(number); // Output: 2 4 6


Back to top