Creating a new List
suggest changeLists can be created in multiple ways.
The recommended way is to use a List literal:
var vegetables = ['broccoli', 'cabbage'];
An empty growable list can also be created with List.empty. The unnamed List() constructor is not available in null-safe Dart:
var fruits = List<String>.empty(growable: true);
If you prefer stronger typing, you can also supply a type argument:
var fruits = <String>['apples', 'oranges'];
For creating a small growable list, either empty or containing some known initial values, the literal form is preferred. There are specialized constructors for other kinds of lists:
// Fixed-length. The element type is nullable because the fill value is null.
var fixedLengthList1 = List<String?>.filled(8, null);
var fixedLengthList2 = List<String>.filled(8, "initial text");
var computedValues = List<String>.generate(8, (n) => "x" * n);
var fromIterable = List<String>.from(computedValues.getRange(2, 5));
See also the Effective Dart style guide about collections.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents