【问题标题】:Meaning of Triple Dots [...] in Flutter SyntaxFlutter 语法中三点 [...] 的含义
【发布时间】:2019-12-03 06:55:13
【问题描述】:

有人能解释一下“...”在 Flutter 中的含义和用法吗?

我想了解 Flutter 语法中使用的“三点”。经过一番阅读,我发现我要找的词是“传播”。

Widget _build() {
  List<Widget> children = [
    Text("first child"),
    Text("second child"),
    Text("third child"),
  ];

  return Column(
    children: <Widget>[
      ...children,
      Text("fourth child"),
    ],
  );
}

如果我在children, 之前没有...,则会出现错误The element type 'List&lt;Widget&gt;' can't be assigned to the list type 'Widget'.

我只是认为有人应该发布一个关于它的问题。什么是颤振语法中的“...”?什么意思?

【问题讨论】:

    标签: flutter syntax


    【解决方案1】:

    Dart 2.3 引入了扩展运算符 (...) 和可识别空值的扩展运算符 (...?),它们提供了一种将多个元素插入集合的简洁方法。

    例如,您可以使用扩展运算符 (...) 将列表的所有元素插入到另一个列表中:

    var list = [1, 2, 3];
    var list2 = [0, ...list];
    assert(list2.length == 4);
    

    如果扩展运算符右侧的表达式可能为空,您可以通过使用可识别空的扩展运算符 (...?) 来避免异常:

    var list;
    var list2 = [0, ...?list];
    assert(list2.length == 1);
    

    有关使用扩展运算符的更多详细信息和示例,请参阅spread operator proposal

    【讨论】:

      【解决方案2】:

      我曾经遇到过这个问题。我通过添加 .toList(); 解决了这个问题;到列表小部件。

      Widget _build() {
      List<Widget> children = [
      Text("first child"),
      Text("second child"),
      Text("third child"),
      ].toList();
      
      return Column(
      children: <Widget>[
        ...children,
        Text("fourth child"),
      ],
      );
      }
      

      希望对你有帮助

      【讨论】:

      • 我的代码实际上正在运行。我只是希望有人发布“...”的明确定义和用法,但感谢您的回答。
      【解决方案3】:

      spread operator (...) 用于提供一种为集合分配值的方法,更常见的是它在列中找到以呈现其子项。

      List<String> values = ['one', 'two', 'three'];
          return Scaffold(
            body: Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ...values.map((value) {
                    return Text(value);
                  }),
                ],
              ),
            ),
          );
      

      输出:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-08
        • 2018-04-29
        • 2018-08-02
        • 2012-03-23
        • 2021-03-05
        • 2018-12-14
        相关资源
        最近更新 更多