Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a "for" loop inside children of a widget?

Tags:

flutter

dart

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.

enter image description here

like image 802
PastuhVu Avatar asked Jun 03 '18 19:06

PastuhVu


People also ask

Is child a widget in flutter?

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.


4 Answers

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()),
);
like image 173
Rémi Rousselet Avatar answered Nov 03 '22 07:11

Rémi Rousselet


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
      ],
    )
    
like image 28
CopsOnRoad Avatar answered Nov 03 '22 08:11

CopsOnRoad


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(),
  ],
]
like image 34
Abhishek Ghaskata Avatar answered Nov 03 '22 07:11

Abhishek Ghaskata


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']),
          ])]
           ),
      }
like image 27
Krishnamoorthy Acharya Avatar answered Nov 03 '22 08:11

Krishnamoorthy Acharya