Suragch
Suragch

Reputation: 511646

How to create an empty list in Dart

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?

Upvotes: 92

Views: 95548

Answers (4)

Nikhil Kadam
Nikhil Kadam

Reputation: 215

List documents = []; empty list of documents

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

Upvotes: 2

Max McKinley
Max McKinley

Reputation: 31

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

Upvotes: 3

Abdulhakim Zeinu
Abdulhakim Zeinu

Reputation: 3829

Fixed Length List

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

Growable List

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

For more refer Docs

Upvotes: 8

Suragch
Suragch

Reputation: 511646

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

Upvotes: 183

Related Questions