How to create an empty list in Dart
Asked Answered
W

4

89

I want to create an empty list for a Flutter project.

final prefs = await SharedPreferences.getInstance();
final myStringList = prefs.getStringList('my_string_list_key') ?? <empty list>;

I seem to remember there are multiple ways but one recommended way. How do I do it?

Weekender answered 4/1, 2019 at 0:11 Comment(0)
W
178

There are a few ways to create an empty list in Dart. If you want a growable list then use an empty list literal like this:

[]

Or this if you need to specify the type:

<String>[]

Or this if you want a non-growable (fixed-length) list:

List.empty()

Notes

Weekender answered 4/1, 2019 at 0:11 Comment(2)
Your are absolutely right, But if you pass "growable: true" to List.empty(growable: true) then this will too become a growable list.Ammoniac
@KhizrAAShaikh, good point.Weekender
B
7

Fixed Length List

 var fixedLengthList = List<int>.filled(5, 0);
 fixedLengthList[0] = 87;

Growable List

var growableList = [];
growableList.add(499);

For more refer Docs

Bim answered 6/9, 2021 at 22:55 Comment(2)
These are for lists that aren't empty.Weekender
The growable list can be empty when declared. I've edited my answer to show that.Bim
G
3

I had this problem as well when I tried List.empty();, but just initializing a list to [] works and makes it append-able.

Germann answered 9/6, 2022 at 18:19 Comment(0)
S
2

List documents = []; empty list of documents

List<'Student'> students = []; empty list of student object or model

Shelve answered 24/2, 2023 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.