How to create an empty list in Dart

ListDartFlutter

List Problem Overview


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?

List Solutions


Solution 1 - List

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

Solution 2 - List

Fixed Length List

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

Growable List

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

For more refer Docs

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuragchView Question on Stackoverflow
Solution 1 - ListSuragchView Answer on Stackoverflow
Solution 2 - ListAbdulhakim ZeinuView Answer on Stackoverflow