'Encase each item inside List<Widget> with a Container

I have a list of Widgets, and I would like to wrap each item inside that list with a Container widget. Take this code as example:

Before:

List<Widget> content = [
  Text('Hello'),
  Text('World'),
  Text('Please'),
  Text('Help'),
];

After:

List<Widget> content = [
  Container(child: Text('Hello')),
  Container(child: Text('World')),
  Container(child: Text('Please')),
  Container(child: Text('Help')),
];

Is there a way to do it programmatically, without actually wrapping all items separately?



Solution 1:[1]

You can make use of map() to make a new list from your list.

example: List newList= content.map((textWidget)=>Container(child: textWidget)).toList();

maybe this can help you to get your result.

Solution 2:[2]

You can map all the element and put inside Container. for example,

List <Widget> newContents = content.map((text)=> Container(child: text)).toList();

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 Avnish Nishad
Solution 2 Rintu Banerjee