PastuhVu
PastuhVu

Reputation: 661

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

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

Upvotes: 65

Views: 183210

Answers (5)

My Car
My Car

Reputation: 4556

If you don't have a List:

ListView(
  scrollDirection: Axis.horizontal,
  children: List.generate(10, (index) => …),
),

Else:

ListView(
  scrollDirection: Axis.horizontal,
  children: list.map((e) => …).toList(),
),

Upvotes: 1

Abhishek Ghaskata
Abhishek Ghaskata

Reputation: 1960

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

Upvotes: 19

CopsOnRoad
CopsOnRoad

Reputation: 267404

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

Upvotes: 41

Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4244

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']),
          ])]
           ),
      }

Upvotes: 5

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276891

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

Upvotes: 98

Related Questions