'Flutter For Loop inside children only allows one widget
I have a For loop inside a listview widget to populate its children. Right now I have one widget my custom history view widget:
Expanded(
flex: 5,
child: Container(
width: double.infinity,
color: Colors.white,
child: ListView(
padding: const EdgeInsets.only(top: 10.0),
children: [
for (var i = Provider.of<WeekList>(context)
.listOfWeeks
.toList()
.length;
i > 1;
i--)
HistoryView(index: i - 2),
],
),
),
)
The problem is I want to add a second widget under the History view widget, but I cant seem to figure out how to correctly do this. I thought it would be as easy as this:
Expanded(
flex: 5,
child: Container(
width: double.infinity,
color: Colors.white,
child: ListView(
padding: const EdgeInsets.only(top: 10.0),
children: [
for (var i = Provider.of<WeekList>(context)
.listOfWeeks
.toList()
.length;
i > 1;
i--){
HistoryView(index: i - 2),
WeekWidget(index: i - 2 ),
}
],
),
),
)
Solution 1:[1]
You can wrap HistoryView and WeekWidget in a column
Solution 2:[2]
Use the spread operator
Expanded(
flex: 5,
child: Container(
width: double.infinity,
color: Colors.white,
child: ListView(
padding: const EdgeInsets.only(top: 10.0),
children: [
for (var i = Provider.of<WeekList>(context)
.listOfWeeks
.toList()
.length;
i > 1;
i--)
...[
HistoryView(index: i - 2),
WeekWidget(index: i - 2 ),
],
],
),
),
)
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 | Manjit2003 |
| Solution 2 | Kedar Karki |
