Dynamic Initialization of List in Dart
The list is a type of datatype in Dart language that acts as an object. It can be used to store various values. In a dynamic List, the values can be of the same data or a combination of different data types(int only or combination of int and string, etc).
Dynamic initialization means that values are inserted into an object by the user. Here the values are not provided by default, rather these are entered by the user during the run time.
Syntax:
List ? list_Name = List.filled(number of elements, E, growanle:boolean);
Here we insert elements into the list dynamically. We can assign values at the start of the program. But to make the program more useful we need to enter elements into the List dynamically. It can be achieved by for/while loop and by defining the size of the List(which is entered by the user using the stdin function from the package dart:io).
Example 1:
Dart
import "dart:io" ;
void main() {
print( "Enter the size of List: " );
int size = int .parse(
stdin.readLineSync()!);
List newlist = new List.filled(size, null,
growable: false );
int i = 0;
while (i < size) {
newlist[i] = stdin.readLineSync()!;
i++;
}
print(newlist);
}
|
Output:
Example 2:
Dart
import "dart:io" ;
void main() {
print( "Enter the size of List: " );
int size = int .parse(stdin.readLineSync()!);
List newlist = new List.filled(size, null,growable: false );
print( "Enter the elements" );
int i;
for (i=0;i<size;++i) {
newlist[i] = stdin.readLineSync()!;
}
print( "The elements in the list are: " );
print(newlist);
print( "The elements in the list with its index are: " );
for (i=0;i<size;++i){
print( "Element at Index $i is $newlist[i]" );
}
}
|
Output:
Last Updated :
29 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...