How to create a list with given length? I want my list to take only 3 variables, it should not expand.
How to do that in Dart / Flutter?
CodePudding user response:
You can use generate
like this:
List result = List.generate(3, (index) => index.toString());// [0,1,2]
CodePudding user response:
Well, you can use List.filled() to make it happen.
This creates a list of the given length with [fill] at each position. The [length] must be a non-negative integer.final zeroList = List<int>.filled(3, 0, growable: true); // [0, 0, 0]
In this way you will have a list with given length, you can only put three variables inside that list, and default variables will be 0.
Here is more detailed information which is quated from #dart-documentation.
The created list is fixed-length if [growable] is false (the default) and growable if [growable] is true. If the list is growable, increasing its [length] will not initialize new entries with [fill]. After being created and filled, the list is no different from any other growable or fixed-length list created using [] or other [List] constructors.
All elements of the created list share the same [fill] value.
final shared = List.filled(3, []); shared[0].add(499); print(shared);
You can use [List.generate] to create a list with a fixed length and a new object at each position.
final unique = List.generate(3, (_) => []); unique[0].add(499); print(unique); // [[499], [], []]