Skip to main content

Flutter Dart Create Fixed Length List Array

Fixed length list array will not change its length after defining once. We will use List filled() method in our tutorial to create fixed length. But there is a catch we can update List items using Index position. Read the below tutorial for more clarity.

Syntax:

final listTemp = List<int>.filled(List Length, Data Filled, growable: false); // [0, 0, 0] 
Explanation:
  • List Length: The first argument in which we will pass length of the list. It always starts from Zero.
  • Data Filled is the data which will filled into all items. We can update them later using Index.
  • growable: Default value is False because we want to create Static list. But we can make this growable by passing True.

Flutter Dart Create Fixed Length List Array

1. Creating Fixed item list with filled() method. We will be creating 10 items array list filled with Zero in each item.
final tempList = List <double>.filled(10, 0);
2. Updating Array List item with Index position.
 //Update Item with Index.
  tempList[0] = 1;
  tempList[1] = 2;
 
  print(tempList);
3. If we trying to call Add() method which add 1 index than it will throw us error because fixed lenght list does not support increase length of list at run time.
  //Throw Error because it is fixed list.
  tempList.add(3);
Source code for main.dart file:
void main() {
  
  final tempList = List <double>.filled(10, 0);
  
  print(tempList);
  
  //Update Item with Index.
  tempList[0] = 1;
  tempList[1] = 2;
 
  print(tempList);
  
  //Throw Error because it is fixed list.
  // tempList.add(3);
  // print(tempList);

}

Output:
Flutter Dart Create Fixed Length List Array

Comments