简体   繁体   English

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

[英]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.我希望我的列表只包含 3 个变量,它不应该扩展。

How to do that in Dart / Flutter?如何在 Dart / Flutter 中做到这一点?

You can use generate like this:您可以像这样使用generate

List result = List.generate(3, (index) => index.toString());// [0,1,2]
  • Well, you can use List.filled() to make it happen.那么,您可以使用 List.filled() 来实现它。
    This creates a list of the given length with [fill] at each position. The [length] must be a non-negative integer.这将创建一个给定长度的列表,每个 position 处都带有 [fill]。[length] 必须是非负数 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.这样你就会得到一个给定长度的列表,你只能在该列表中放置三个变量,默认变量将为 0。


Here is more detailed information which is quated from #dart-documentation.这是从#dart-documentation 中引用的更详细的信息。

The created list is fixed-length if [growable] is false (the default) and growable if [growable] is true.如果 [growable] 为 false(默认值),则创建的列表是固定长度的,如果 [growable] 为 true,则创建的列表是可增长的。 If the list is growable, increasing its [length] will not initialize new entries with [fill].如果列表是可增长的,增加它的 [length] 将不会用 [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.创建并填充后,该列表与使用 [] 或其他 [List] 构造函数创建的任何其他可增长或固定长度列表没有什么不同。

  • All elements of the created list share the same [fill] value.创建的列表的所有元素共享相同的 [fill] 值。

     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.您可以使用 [List.generate] 创建一个固定长度的列表,并在每个 position 处创建一个新的 object。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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