Open In App

Dynamic Initialization of List in Dart

Improve
Improve
Like Article
Like
Save
Share
Report

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




//Dynamic Initialization of List in Dart
 
import "dart:io";
 
void main() {
  print("Enter the size of List: ");
  int size = int.parse(
      stdin.readLineSync()!); //Takes the size of the list from the user
  List newlist = new List.filled(size, null,
      growable: false); //Declaring a list with the size user entered
 
//Loop for taking each value
  int i = 0;
  while (i < size) {
    newlist[i] = stdin.readLineSync()!;
    i++;
  }
 
  print(newlist); //Print all the values user entered in the List
}


Output:

 

Example 2:

Dart




//Dynamic Initialization of List in Dart
 
import "dart:io";
 
void main() {
  print("Enter the size of List: ");
  int size = int.parse(stdin.readLineSync()!);
  //Takes the size of the list from the user
   
  List newlist = new List.filled(size, null,growable: false);
  //Declaring a list with the size user entered
  print("Enter the elements");
 //Loop for taking each value
  int i;
for(i=0;i<size;++i) {
    newlist[i] = stdin.readLineSync()!;
  }
  print("The elements in the list are: ");
  print(newlist);
  //Print all the values user entered in the List
   
  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
Previous
Next
Share your thoughts in the comments
Similar Reads