简体   繁体   中英

Create a list of the given length in Dart/Flutter

How to create a list with a given length? I want my list to take only 3 variables, it should not expand.

How to do that in Dart / Flutter?

You can use generate like this:

List result = List.generate(3, (index) => index.toString());// [0,1,2]
  • 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], [], []]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM