在 Dart/Flutter 中创建给定长度的列表

问题描述 投票:0回答:3

如何创建给定长度的列表?我希望我的列表只包含 3 个变量,它不应该扩展。

如何在 Dart / Flutter 中做到这一点?

flutter list dart maxlength
3个回答
6
投票
  • 好吧,你可以使用 List.filled() 来实现它。
    这将创建一个给定长度的列表,每个位置都有 [fill]。 [长度]必须是非负整数。

          final zeroList = List<int>.filled(3, 0, growable: true); // [0, 0, 0]
    

这样你就会得到一个给定长度的列表,你只能在该列表中放入三个变量,默认变量将为0。


这里有更详细的信息,引用自#dart-documentation。

如果 [growable] 为 false(默认),则创建的列表是固定长度的;如果 [growable] 为 true,则创建的列表是可增长的。如果列表可以增长,则增加 它的[length]不会用[fill]初始化新条目。创建并填充后,列表与使用 [] 或其他 [List] 构造函数创建的任何其他可增长或固定长度列表没有什么不同。

  • 创建的列表中的所有元素共享相同的[填充]值。

      final shared = List.filled(3, []);
      shared[0].add(499);
      print(shared);
    
  • 您可以使用[List.generate]创建一个固定长度的列表,并在每个位置创建一个新对象。

      final unique = List.generate(3, (_) => []);
      unique[0].add(499);
      print(unique); // [[499], [], []]
    

5
投票

您可以像这样使用

generate

List result = List.generate(3, (index) => index.toString());// [0,1,2]

0
投票
> In this example, List<int>(3) initializes a fixed-length list of integers with a length of 3. You can access and modify elements using their indices as shown above. It's important to note that you cannot add or remove elements from this list since its length is fixed.

If you try to add more than three elements or modify the list's length, you will encounter an error. This makes sure that the list maintains its fixed size.
  

  void main() {
      List<int> fixedLengthList = List<int>(3);
      fixedLengthList[0] = 1;
      fixedLengthList[1] = 2;
      fixedLengthList[2] = 3;
    
        enter code here
    
      print(fixedLengthList); // Output: [1, 2, 3]
    }
© www.soinside.com 2019 - 2024. All rights reserved.