I am really confused with this, where should the FOR LOOP be placed, so that I don't get an error in flutter? As you can see on the picture, it has red underlines and it says.
Center is the child widget of the Container widget. Again, Text is the child of the Center widget. Text is used to show message and Center is used to center the text message with respect to the parent widget, Container.
Two alternatives :
final children = <Widget>[];
for (var i = 0; i < 10; i++) {
children.add(new ListTile());
}
return new ListView(
children: children,
);
or
return new ListView(
children: new List.generate(10, (index) => new ListTile()),
);
There are multiple ways of using a for
loop in children for widgets like ListView
, Column
, etc.
Using a for
loop
ListView(
children: [
for (var i = 0; i < 10; i++) Text('Item $i'),
],
)
Using a for-each
loop
ListView(
children: [
for (var item in items) Text(item),
],
)
Combining ...[]
with for
loop
ListView(
children: [
...[
Text('Item 0'),
Text('Item 1'),
],
for (var item in items) Text(item), // Rest of the items
],
)
We can use the spread operator also to add multiple widgets using for the loop
Column(
children: [
Container() /// we can add some other widgets
for (var i = 0; i < 3; i++) ...[
CardListItem(),
Divider(),
],
]
Simple for loop in flutter using json response
Widget build(BuildContext context) {
var list = [{'id':"123123","date":"20/08/2016"},{'id':"123124","date":"26/08/2016"},{'id':"123125","date":"26/08/2016"}];
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text('Recent Claims'),
Table(
border: TableBorder.all(color: Colors.black),
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(100.0)
},
children:[
for(var item in list ) TableRow(children: [
Text(item['id']),
Text(item['date']),
])]
),
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With