Is it possible to initialize a List on one line in Dart? (it's called a collection initializer in c#)

Solution 1:

Yes:

List<int> options = [1, 2, 5, 9];

I'd recommend reading:

  • https://api.dartlang.org/stable/1.24.3/dart-core/List-class.html

Solution 2:

Yes, you can do it using the List.unmodifiable constructor:

var options  = new List.unmodifiable([3,6,7,8]);

Or by using the List.from constructor:

var options  = new List.from([3,6,7,8]);

Or just like this:

var options  = [5,7,9,0];

Solution 3:

There are also available List.filled and List.generate factory constructors:

List<int?> s = List.filled(5, 10, growable: true); // [10, 10, 10, 10, 10]

This creates list of length 5, of type int or null, and initializes each element with 10. This list is growable, which means its length can be changed with a setter:

s.length = 10;
s[8] = 2;  // [10, 10, 10, 10, 10, null, null, null, 2, null]

After changing the list length, new elements will be initialized with null. If the list element type is not-nullable this will cause Exception.

List.generate generates a list of values.

var n = List.generate(5, (index) => 0); // [0, 0, 0, 0, 0]

The created list is fixed-length, and each element is set to 0.

List<int?> n = List.generate(5, (index) => index * index, growable: true); // // [0, 1, 4, 9, 16]

If we want to create growable list (i.e. we set growable to true) we need to explicitly choose non-nullable type eg. int? as we did here, otherwise increasing list length will raise exception. This stands for both List.generate and List.filled factories.

Good reads about those are:

https://api.dart.dev/stable/1.24.3/dart-core/List/List.generate.html and https://api.dart.dev/stable/1.24.3/dart-core/List/List.filled.html

Solution 4:

  var vals = <int>[1, 2, 3];
  var vals2 = List<int>()..addAll([1, 2, 3]);
  var vals3 = List<int>.of([1, 2, 3]);

Note that when we don't provide a type, we in fact create a list of a dynamic type. Also, the new keyword is optional.