How to create a list in Flutter

October 09, 2022 No comments dart flutter list

Introduction

Sometimes, we'll like to create a list which is a standard object that contains other items in an orderly manner. In this post, we'll describe how to create fixed-length and growable lists in Flutter/Dart.

How to create a list in Flutter

To create a fixed-length list in Flutter we use the List() constructor and give a size of the list:

List<String> list = List<String>(3);
list[0] = '1';
list[1] = '2';
list[2] = '3';
list[3] = '4';

print(list);

The output:

[1, 2, 3, 4]

To create a growable list in Flutter we also use the List() constructor but without specifying the length of the List:

List<int> list = List<int>();
list.add(10);
list.add(20);
list.add(30);

print(list);
print(list.length);

list.add(40);
print(list);
print(list.length);

The output:

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

Note that Flutter allows adding null to Lists:

List<int> list = List<int>();
list.add(10);
list.add(null);
list.add(30);

print(list);

The output:

[10, null, 30]

Conclusion

In this short tutorial, we presented how to create a List in Flutter. There are two kinds of lists in Flutter/Dart: with fixed-length and growable, you can decide which is the best for your application.

{{ message }}

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