For Loop in Flutter

 For loop is used when you want to use the index.

The syntax of for loop is as follows:

for(variable;condition;increment)

  {

     body

  }

There are multiple ways of using a for loop in children for widgets like ListView, Column, etc.

  • Using a for loop

ListView( children: [ for (var i = 0; i < 10; i++) Text('Item $i'), ], )

  • Using a for-each loop

ListView( children: [ for (var item in items) Text(item), ], )

  • Combining ...[] with for loop

ListView( children: [ ...[ Text('Item 0'), Text('Item 1'), ], for (var item in items) Text(item), // Rest of the items ], ).

 

Example:

How to use For Loop to generate a list of Widgets in Flutter?

Generally, this kind of list is used where we are not sure of the size of data or we can say that based on the dynamical size of a widget.

Suppose a user is having a list like the below:

Consider a code snippet like the below:

@override

  Widget build(BuildContext context) {

    List<int> text = [1,2,3,4];

    return Scaffold(

      appBar: AppBar(

        title: Text(widget.title),

      ),

      body: Container(

        child: Column(

          children: [

            for ( var i in text ) Text(i.toString())

          ],

        ),

      ),

    );

Another method that was provided before dart 2.3 is this:

@override

Widget _getListWidgets(List yourList){

return Row(children: yourList.map((i) => Text(i)).toList());

 }

 

You can try the .map method like below:

class Example extends StatelessWidget {

  List <int> exampleList =  [1,2,3,4];

  @override

  Widget build(BuildContext context) {

    return

      Container(

        child: Column(

            children: exampleList.map((i) => new Text(i.toString())).toList()

        ),

      );

  }

}

This method will come in handy if you have objects inside your list. Also with the .map() method .toList() must be used at the end.

You could use the map method of your list of Strings.

Widget _getListWidgets(List<String> yourList){

   return Row(children: yourList.map((i) => Text(i)).toList());

 }

When your List has a complex Object:

Widget _getListWidgets( List<YourObject> lstItens) {

  return Row(children: lstItens.map((i) => Text(i.name)).toList());

}

Example:

void main() {

  for (var i=0; i<5; i++){

    print(i);

  }

}

 

OutPut:

0

1

2

3

4


Advertisements