Reputation: 511646
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
Reputation: 215
List documents = [];
empty list of documents
List<'Student'> students = [];
empty list of student object or model
Upvotes: 2
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
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
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()
List()
but this is now deprecated. The reason is that List()
did not initialize any members, and that isn't compatible with null safe code. Read Understanding null safety: No unnamed List constructor for more.Upvotes: 183