×

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

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.

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 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 Function

A Dart function is a collective line of code that are targeted to perform a specialised task. Such lines of code (function) can be reused whenever we need to perform...

6 minutes read.

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

Dart Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable...

4 minutes read.

Dart Miscellaneous types

Some Other Data types in Dart Apart from the data types studied so far, we have three other data types also which are as follows: NeverDynamicVoid Let us understand each one in detail, Never...

3 minutes read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Dart Construtors

Constructors are the very important concept in any programming language. They are the special functions created in the classes to allocate memory to the objects of that class when created...

4 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes 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 Important Concepts

1. Anything placed in a variable is an object, and an object is an instance of a class. Numbers, functions, and null are all objects in Dart, and all these...

3 minutes read.

Dart Static Members

Static Members in Dart Static members are the members of the class declared using the 'static' keyword. the static members have the following characteristics :  All the objects of the class having...

3 minutes 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 Concurrency

Dart concurrency allows us to run multiple or multiple components of a system at once. It issues several commands at once. Dart provides Isolates as a tool for performing compliance...

2 minutes read.

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.

Typedef in Dart

In Dart, typedef is used to generate a function type that we can use as a type annotation for declaring variables and return types of the function type. An alias...

4 minutes read.

Dart lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Dart Logical Operators

Logical operators are the operators that combine two or more conditions, and accordingly return a Boolean value : true or false. Assume the value of variable A is 25 and B...

2 minutes read.