Home > Software engineering >  How can I make Widget using iterator like 'for' in Flutter?
How can I make Widget using iterator like 'for' in Flutter?

Time:10-02

I wanna make a number of widgets in the ListView by using iterator like for, like the example below,

for(int i = 1; i < 3; i   ){
 Text('hello world'),
}

but unfortunately it doesn't work, showing me this error message.

The element type 'Set<Text>' can't be assigned to the list type 'Widget'.

How can i fix this?

Thank you for concerning my question.

CodePudding user response:

For ListView you can use List.generate.

...
body: ListView(
  children: List.generate(
    10,
    (index) => ListTile(
      title: Text(index),
    ),
  ),
),
...

If you are traditional and wanna use for then go for it like this,

...
body: ListView(
  children:[ 
    for(int i = 0; i < 5; i  )
    ListTile(title:Text("$i")),
  ]
),
...

If you have a very big list then consider using ListView.builder. Why? Because it renders only the widgets that are available on the screen which would be pretty fast to load. This is how to use it,

...
body: ListView.builder(
  itemCount: 20,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text("$index"),
    );
  }
),
...
  • Related