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

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(),
  ],
]

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()),
);

Tags:

Dart

Flutter