Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop inside widget in flutter

Tags:

flutter

dart

How do I use a loop inside a widget?

I want to be able to:

RichText(
 text: TextSpan(
 text: 'Itemlist\n',
 children: <TextSpan>[

     
   for(i = 0; i< items.length; i++){

     TextSpan( text: 'item' +i +': ',),
     TextSpan( text: 'item[i].value' +i +'\n',),


     }
 
  ]
)

it is importaint that i could have several lines of code inside the loop.

like image 383
cueless Avatar asked Jun 21 '26 07:06

cueless


1 Answers

You can achieve by spread operator which unfold the Iterable<Widget> as follows:

RichText(
  text: TextSpan(
    text: 'Items\n',
    children: <TextSpan>[
      for(var i = 0; i< items.length; i++)
        ...[
          TextSpan( text: 'Item ${i.toString()}: '),
          TextSpan( text: '${items[i]} \n',),
        ],
    ],
  ),
)

You can check it out in DartPad also.

like image 192
saw Avatar answered Jun 23 '26 11:06

saw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!