3

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.

4
  • You just need to put your for loop (put ANY code) inside of a function or method. In your case, I'd create a function that returns an array of <TextSpan>[] widgets. Commented Mar 18, 2022 at 16:31
  • Try to understand the pain of a beginner. Please try to Share the solution Commented Mar 18, 2022 at 16:33
  • ok thanks I understand, thats the way its done in flutter? Commented Mar 18, 2022 at 16:34
  • Great to read @cueless Commented Mar 18, 2022 at 16:35

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How is this answer so underrated! Lifesaver...

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.