84

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?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

4 Answers4

171

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

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
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

Abdulhakim Zeinu
  • 3,333
  • 1
  • 30
  • 37
3

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

1

List documents = []; empty list of documents

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

Nikhil Kadam
  • 109
  • 4