2

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.

2
  • 1
    for(int i = 1; i < 3; i++ ) Text('hello world'), Commented Oct 2, 2021 at 6:17
  • 1
    See stackoverflow.com/a/66126532. Commented Oct 2, 2021 at 6:36

1 Answer 1

3

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"),
    );
  }
),
...
Sign up to request clarification or add additional context in comments.

1 Comment

I solved the problem with second manner, thank you very much!!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.