How to initialize List with values in Flutter

October 09, 2022 No comments flutter dart list initialize

Introduction

In Flutter/Dart, we may need to initialize a List with values. In this article, we present several methods of how to do it.

How to initialize List with values in Flutter

In Flutter we can initialize a list simply using the [] operator:

List<int> list1 = [40, 30, 20, 10];
print(list1);

var list2 = ['first', 'second', 3, 4];
print(list2);

The output:

[40, 30, 20, 10]
[first, second, 3, 4]

To initialize a fixed-size list in Flutter we can use the filled() constructor:

var listWithFixedSize = List.filled(1, 2, 3);  // we cannot add any more items to that list
print(listWithFixedSize);

The output:

[1, 2, 3]

To initialize a growable list in Flutter we use the filled() constructor with the growable: true attribute:

var thisIsGrowableList = List.filled(1, 2, 3, growable: true);
thisIsGrowableList.add(4);
print(thisIsGrowableList);

The output:

[1, 2, 3, 4]

To initialize a list in Flutter we can also use the from() constructor that works similar to filled():

var listWithFixedSize = List.from([1, 2, 3], growable: false);  // we cannot add any more items to that list
print(listWithFixedSize);

var thisIsGrowableList = List.from([1, 2, 3]);
thisIsGrowableList.add(4);
print(thisIsGrowableList);

The output:

[1, 2, 3]
[1, 2, 3, 4]

The difference between filled() and from() constructor is that filled() by default creates fixed-size list and from() creates by default growable list.

In Flutter there is also a constructor generate() that can be used to create a list of items:

var sampleList = List.generate(4, (index) => index * 2);
print(sampleList);

The output:

[0, 2, 4, 6]

Conclusion

In this short article, we presented methods to initialize a list in Flutter/Dart.

{{ message }}

{{ 'Comments are closed.' | trans }}