×

Dart Generators

Synchronous Generator

Dart Generator is a unique function that allows us to generate price sequences. Generators return values when needed; means that the value is generated if we try to duplicate the iterators. Dart provides built-in support between two types of generator functions which are as follows:

• Synchronous Generators

• Asynchronous Generators

Returns the tangible object containing the synced value. The keyword ‘ yield ’ is used in conjunction with the body of the synchronous generating function as ‘ sync * ’ in production values.

Let's understand the following example of a synchronous generator.

Example -

// Program of Dart Synchronous Generator 
void main( )  
{  
    print( " This is the list of even numbers between 1 to 15  : " ) ;  
    oddNumber( 15 ).forEach( print ) ;   
} 
// sync* functions returns an iterable  
Iterable< int > oddNumber( int n ) sync* 
{  
    int temp = n ;  
    while( temp >= 0 ) 
    {  
         if( temp % 2 == 1 ) 
         {  
            // ' yield ' statement
            yield temp ;  
         }  
      temp-- ;  
    }  
}  

Output :

This is the list of even numbers between 1 to 15  :
15
13
11
9
7
5
3
1

Explanation :

In the above program, we announced the work of oddNumber (10) with the front loop outside its body. The previous loop will repeat the operation. Now, we have created the oddNumber (10) function as a compatible generator function.

In the working body, we have introduced a new k, which gives the argument n. Then, we applied while the loop repeated the function, and the loop body is repeated until the value of k is less than or equal to 0.

We performed modulus operation on k to obtain odd numbers from the generators. We have used a yield statement, which suspends work performance and returns value on time. It will reimburse you for each production activity. If the loop position is false, the loop is disconnected and print odd numbers.

Asynchronous Generators

Returns a broadcast object with equal value. Yield keyword is used in conjunction with the non-synchronized generator operating body as async * in production values.

Let's understand the following example -

Example -

// Program of Dart Asynchronous Generator 
void main( )  
{  
    print( " List of first 15 whole numbers are as follows : " ) ;  
    asyncNaturalsTo( 15 ).forEach( print ) ;   
}    
// async* functions returns a stream object  
Stream< int > asyncNaturalsTo( int num ) async* 
{  
    int temp = 0 ;  
    while( temp < num ) 
    {  
        // ' yield ' statement  
        yield temp++ ;   
    }  
  temp-- ;  
}

Output :

List of first 15 whole numbers are as follows : 
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Explanation :

The code above generates the corresponding values. The asyncNaturalsTo (int num) function returns the broadcast material to each signature of the task body. Here, the keyword crop behaves in the same way as the previous example; paused performance, restored value, and resumed performing subsequent repetitions. It will happen again and again until the active body is discontinued.

Let's understand the following concepts related to generator function.

The yield Keyword

The keyword ‘ yield ’ returns one value in sequence at a time but does not completely prevent the production of production. It returns the value of each production function.

The sync* Keyword -

To denote the function of the sync generator we use the keyword ‘ sync* ’. It returns value when we try to multiply value not when created. Let's look at the following example -

Example -

// Iterators in Dart 
void main( ) 
{  
  print( ' Defining iterators in Dart : ' ) ;  
  Iterable< int > numbers = getNumbers( 5 ) ;  
  
  // Here we are creating iterator  
  print( ' Beginning of the iterator function ' ) ;  
  for ( int num in numbers ) 
  {  
    // Iterating over the iterator
    print( ' $num ' ) ;          
  }  
  print( ' End of main( ) function ' ) ;  
}  
Iterable< int > getNumbers( int n ) sync* 
{            
  // This is a synchronous generator  
  for ( int i = 0 ; i < n ; i++ ) 
  {  
    yield i ;  
  }  
  print( ' End of the iterator function ' ) ; 
} 

Output :

Defining iterators in Dart : 
 Beginning of the iterator function 
 0 
 1 
 2 
 3 
 4 
 End of the iterator function 
 End of main( ) function 

Explanation -

The above production function produces a value when we multiply over the iterator.

The async* Keyword

The async keyword is used to declare the asynchronous generators. It returns the stream object. Let's understand the following example -

Example -

void main( ) 
{  
  print( ' Defining an iterator ' ) ;  
  Stream< int > numbers = getNumbers( 5 ) ;  
  
  print( ' Beginning of the iterator : ' ) ;  
  numbers.listen( ( int num ) 
  {  
    print( ' $num ' ) ;  
  } ) ;  
  print( ' End of the main( ) function ' ) ;  
} 


Stream< int > getNumbers( int number ) async* 
{  
  // declaring asynchronous generator function  
  print( ' Applying a delay of 4 seconds inside the generator : ' ) ;   
  await new Future.delayed( new Duration( seconds : 4 ) ) ; // sleep for 4 second  
  
  print( ' Generator started generating values... ' ) ;  
  
  for ( int i = 0; i < number; i++ ) 
  {  
    await new Future.delayed( new Duration( seconds : 2 ) ) ; // sleep for 2 seconds  
    yield i ;  
  }  
  print( ' Generator ended generating values... ' ) ;  
}  

Output :

Defining an iterator 
 Beginning of the iterator : 
 End of the main( ) function 
 Applying a delay of 4 seconds inside the generator: 
 Generator started generating values... 
 0 
 1 
 2 
 3 
 4 
 Generator ended generating values...

Related Topics

Dart Operators Precedence and Associativity

Precedence of operators determines the order in which the operators are evaluated if they are grouped together in a sentence. If two operators share an operand then the one with...

5 minutes read.

Dart Iterable

Iterable is a collection of elements that are accessed sequentially. These elements are accessible using the iterator getter and stepping through the values using this getter. Let us understand the setting...

6 minutes read.

Golang vs Dart

Go is the procedural programming language. It was founded in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but was launched in 2009 as the language of...

2 minutes read.

Dart Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

2 minutes read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

4 minutes read.

Dart Strings

Strings data type in Dart A Dart string is a sequence of characters with an encoding of UTF-16. The text associated with string data type is enclosed withing single (‘  ’)...

3 minutes read.

Dart Built-in Data Types

A data type defines the type of value a variable can hold, such as integer, double, or string.  Dart supports two data types:  1. Built-in data types : These are the data...

1 minute read.

Dart - Control Flow Statements

The control flow statements are used to define the control on the flow of the program. Dart programs are executed in sequential order i.e., the order in which the programming...

1 minute read.

Dart Booleans

Booleans Dart has a data type named ‘bool’ to represent Boolean values : true and false, which are compile-time constants. ‘True’ or ‘False’ cannot be assigned with values 1 or 0. Example, bool...

1 minute read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.

Dart Generics

Dart Generics is similar to Dart collections, which are used to store homogeneous data. As we have discussed in Dart's features, it is a language with types being optional. By default,...

4 minutes read.

Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.

Dart Anonymous Function

Dart functions are the user defined functions that are designed to perform specific task. The use case of the functions is that they can be directly called any number of...

3 minutes read.

Dart URIs

The Uri class supports encoding and decoding of strings with the help of functions to be used in URIs ( which may also be known as URLs ). These functions...

6 minutes read.

Dart Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

9 minutes read.

Dart Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart Runes and Graphemes

Runes and Graphemes data types in Dart Runes and Graphemes Runes are the special string of Unicode UTF-32 bits that represent the special syntax. Unicode defines a unique numeric value for each...

2 minutes read.

Interfaces in Dart

An interface in Dart refers to the syntax or blueprint that any class must adhere to. It basically defines the array of methods available on the object. It provides the...

3 minutes read.

Dart Tutorial

Dart is an open-source, structured programming language developed by Google. It is a high-level programming language that emerged in 2011, but its stable version emerged in 2017. It is largely used...

4 minutes read.