如何将Widget列表传递给另一个Widget的children属性?

10
以以下函数为例:
List<Widget> getListFiles() {
    List<Widget> list = [
        Container(),
        Container(),
        Container(),
    ];

    return list;
}

如何向子参数中插入内容?
Column(
    children: <Widget>
    [
        Text(),
        Text(),
        getListFiles(), <---
        Text(),
    ]
)
3个回答

23

更新

现在Dart有版本2.3的传播运算符。

[
  ...anotherList
  item1
]

不使用Spread操作符的答案

我认为您需要展开列表,因为您无法将元素类型'List'分配给列表类型'Widget'。 Spread操作符是一个期望的功能。 您可以在此处关注它的问题。

与此同时,您可以使用生成器yield操作符。

Column(
  children: List.unmodifiable(() sync* {
    yield Text();
    yield Text();
    yield* getListFiles();
    yield Text();
  }()),
);

在小部件中使用的完整代码。

import 'package:flutter/material.dart';

class App extends StatelessWidget {
  List<Widget> getListFiles() {
    List<Widget> list = [Text('hello'), Text('hello1'), Text('hello2')];

    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stackoverflow'),
      ),
      body: Column(
        children: List.unmodifiable(() sync* {
          yield Text('a');
          yield Text('b');
          yield* getListFiles();
          yield Text('c');
        }()),
      ),
    );
  }
}

5

现在您可以使用扩展运算符 - 自Dart 2.3.0起

Column(
    children: <Widget>
    [
        Text(),
        Text(),
        ...getListFiles(), <---
        Text(),
    ]
)

此外,您可能需要在pubspec.yaml中将最低SDK级别更改为2.3.0。

0
假设您有一组自定义小部件要在中显示。 < p > < em > 自定义小部件
class Answer extends StatelessWidget {
  final VoidCallback selectHandler; // property holds the function.
  final String answerText;

  ...
}

使用列表字面值:以下是在列中调用Answer Widget列表的方法,
 Column(
      children: [
        const Text('Question'),
        ...([
          Answer(_answerQuestion, 'Answer 1'),
          Answer(_answerQuestion, 'Answer 2')
        ])
      ],
    )

从列表中:利用列表属性映射自定义小部件列表。

// List<String> property.
var answers = ['Black', 'Red', 'Green'];
// Pass in the list of custom widgets inside Column as follows.
...answers.map((answer) => Answer(_answerQuestion, answer))

使用List<Map<String,Object>>列表:如果您有一个复杂的结构,请从“答案”列表准备自定义小部件Answer,如下所示。

// List<Map<String, Object>> property. 
var questions = [
  {
    'questionText': 'What\'s your favorite color?',
    'answers': ['Black', 'Red', 'Green']
  }
];
    
// Pass in the list of custom widgets inside Column as follows.
...(questions.first['answers'] as List<String>)
                .map((answer) => Answer(_answerQuestion, answer))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接