Home > OS >  for loop inside widget in flutter
for loop inside widget in flutter

Time:03-19

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.

CodePudding user response:

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.

  • Related