'How to pass List of Widgets in children property of another Widget?

Taking the following function as example:

List<Widget> getListFiles() {
    List<Widget> list = [
        Container(),
        Container(),
        Container(),
    ];

    return list;
}

How to insert into a children param?

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


Solution 1:[1]

Now you can use the spread operator - Since dart 2.3.0

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

Additionally you may have to change the minimum SDK level in the pubspec.yaml to 2.3.0

Solution 2:[2]

Suppose, you have a list of custom widgets to show in the Column.

Custom Widget

class Answer extends StatelessWidget {
  final VoidCallback selectHandler; // property holds the function.
  final String answerText;

  ...
}

Using List Literal: The list of Answer Widget can be called inside column as below,

 Column(
      children: [
        const Text('Question'),
        ...([
          Answer(_answerQuestion, 'Answer 1'),
          Answer(_answerQuestion, 'Answer 2')
        ])
      ],
    )

From List: Map list of custom widgets with help of list property.

// 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))

Using the list from List<Map<String, Object>>: If you have a complex structure, preparing custom widgets of Answer from the list of 'answers' will be implemented as below.

// 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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pulin Shah
Solution 2 Kiran Jasvanee