如何在dart中传播列表

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

在Javascript中我会使用扩展运算符:

enter image description here

现在我和Flutter有同样的问题:

 Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        MyHeader(),
        _buildListOfWidgetForBody(), // <- how to spread this <Widget>[] ????
        MyCustomFooter(),
      ],
    );
  }
dart flutter
3个回答
14
投票

你现在可以用Dart 2.3进行传播

var a = [0,1,2,3,4];
var b = [6,7,8,9];
var c = [...a,5,...b];

print(c);

3
投票

你没有,at the moment。但是你可以从中构建一个List并随时插入/添加其他元素。

 Widget build(BuildContext context) {
   final List<Widget> columnWidgets = List.from(_buildListOfWidgetForBody())
                       ..insert(0, MyHeader())
                       ..add(MyCustomFooter());

    return Column(
          children: columnWidgets
        );   
    }

Update - 20th April 2019

从Dart 2.3发布以来,您现在可以使用扩展运算符。

List<int> a = [0,1,2,3,4];
List<int> b = [6,7,8,9];
List<int> c = [...a,5,...c];

2
投票

将此添加到dart https://github.com/dart-lang/language/issues/47的未来版本中存在问题

但是现在你可以使用sync*yield*

Iterable<Widget> _buildChildren sync* {
  yield MyHeader();
  yield* _buildListOfWidgetForBody();
  yield MyCustomFooter();
}

编辑:从Dart 2.3开始,您现在可以:

Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        MyHeader(),
        ..._buildListOfWidgetForBody(),
        MyCustomFooter(),
      ],
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.