Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Dart Iterables

In Dart, an iterable is any object that can provide a sequence of values. It's a fundamental concept in Dart's collection library and is widely used in Dart programming. Dart provides built-in support for iterables through various classes and interfaces, making it easy to work with collections of data.


Creating Iterables:

List

var numbers = [1, 2, 3, 4, 5];


Set

var uniqueNumbers = {1, 2, 3, 4, 5};


Map (Iterable of key-value pairs):

var keyValuePairs = {'a': 1, 'b': 2, 'c': 3};


2. Iterating Over Iterables:
Using for in loop:

for (var number in numbers) {
print(number);
}

Using forEach Method:

numbers.forEach((number) => print(number));


3. Higher Order Function

Mapping Elements

var doubledNumbers = numbers.map((number) => number * 2);
print(doubledNumbers.toList()); // Output: [2, 4, 6, 8, 10]


Filtering Elements:

var evenNumbers = numbers.where((number) => number % 2 == 0);
print(evenNumbers.toList()); // Output: [2, 4]



4.Generating Sequences Lazily:
Using Generator Functions (Sync*):

Iterable < int> countTo(int n) sync* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
void main() {
var sequence = countTo(5);
print(sequence.toList()); // Output: [1, 2, 3, 4, 5]
}

5.Combining Iterables:
Using Spread Operator:

var combinedList = [...numbers, ...evenNumbers];
print(combinedList); // Output: [1, 2, 3, 4, 5, 2, 4]

Using Collection For Clause:

var doubledEvenNumbers = [for (var num in evenNumbers) num * 2];
print(doubledEvenNumbers); // Output: [4, 8]


6.Lazy Evaluation:
Lazy Evaluation Example:

var lazySequence = numbers.map((number) {
print('Doubling $number');
return number * 2;
});
print('Lazy sequence created');
print(lazySequence.take(2).toList()); // Output: Doubling 1, Doubling 2






Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java