Susana Restrepo
Susana Restrepo

Reputation: 3

How to make a list with a for in Dart

This is my first question so I'm sorry if it's not well formatted.

So, I have this object called book with the property "rating," which is an int of the number of stars. My idea is to show in a row said rating as icons and I thought I'd do it with a spread operator and a for.

I don't know if it's possible because I don't find any documentation about it or if the syntax is wrong because it expects and identifier and a ')' See issue. I would appreciate help with this.

child: Row(
   children: [...(for (var i = 0; i < book.rating; i++) => Icon(Icons.star))],
),

Upvotes: 0

Views: 217

Answers (2)

KuKu
KuKu

Reputation: 7512

You can also made by using List generate.

Row(
      children: List<Widget>.generate(book.rating, (idx) => Icon(Icons.star)),
    );

Upvotes: 1

Tirth Patel
Tirth Patel

Reputation: 5746

There are syntax errors. Remove =>, () from start, ...:

child: Row(
   children: [for (var i = 0; i < book.rating; i++) Icon(Icons.star)],
),

Upvotes: 0

Related Questions