List.generate constructor - List class - dart:core library - Flutter

 

              How to use list generate in Dart


  List generate in Dart and Flutter

In Dart, the core library provides an utility method to handle value generation for List data structure, since generation or making dummy data is a pretty common task. Here the definition:

Now Let us See how to Create a long List using List.generate Method

Syntax of List.generate method

  List<E>.generate( int length, ( index){// function to be Excuted})

1, The first parameter is to specify the size of the list.

2, The second parameter is a generator function that produces list values. The second parameter that means index performs some operation for each index value from        (0--length-1 ))

However, it has bottleneck, because the generator for each index works in range from 0 to length - 1 in increasing order. Hence, we can either generate based on index value or we don’t use index of generator.

To make it practical, following are several examples to demonstrate.

1. Generate a list of numbers

A, This one will generate all numbers from 1 to 10.

List<int>Number= List<int>.generate(10, (index)=>index+1)

B, We can generate all square numbers.

List<int>squareNumber=List<int>.generate(10,(index)=>index*index)

2. Generate a list of dummy text

//Now Let us Create a list of Long String

List<String>longlist= List<String>.generate(10,(index)=>"this is the $index String")

A, now let us generate a log String List or name list from the class below using list.generate.

class person{
late name;
late String fathername;
//class constructor
person(this.name,this.fathername)
}

List<person>personname=List<person>.generate(10, (index){
return person("solomon","Girma");

})

Then you can put this dummy list into listview widget to render.

Summary

It is simple and straight-forward to use list generate












No comments

Powered by Blogger.