How to Iterate through a List to Render a Multiple Widget In Flutter?

· 3 min read
How to Iterate through a List to Render
How to Iterate through a List to Render

When designing an application sometimes the user may require to display data based on some criteria. So, in this article, we will see how to Iterate through a List and Display data in a Flutter.

How to Iterate through a List to Render a Multiple Widget In Flutter?

Generally, users get a list of data from the backend and the user wants to display only a few data. To do this user needs to Iterate through a List and display data. To understand it clearly consider a case where the user has a list. And the user needs to display data based on the size of a list. Consider a list like the below:

var list = ["one", "two", "three", "four"];

Basically, when you hit ‘return’ on a function the function will stop and will not continue your iteration, so what you need to do is put it all on a list and then add it as a child of a widget. Create a Text Widget like the below:

Widget getTextWidgets(List<String> strings)
 {
   List<Widget> list = new List<Widget>();
   for(var i = 0; i < strings.length; i++){
       list.add(new Text(strings[i]));
   }
   return new Row(children: list);
 }

You can also try the below things:

Widget getTextWidgets(List<String> strings)
  {
    return new Row(children: strings.map((item) => new Text(item)).toList());
  }

Try the below code:

child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
             for(var item in list ) Text(item)
          ],
        ),

You can also try the below way:

List<Widget> widgets = list.map((name) => new Text(name)).toList();

Create a widget like the below:

Widget listOfWidgets(List<String> item) {
  List<Widget> list = List<Widget>();
  for (var i = 0; i < item.length; i++) {
    list.add(Container(
        child: FittedBox(
          fit: BoxFit.fitWidth,
          child: Text(
            item[i],
          ),
        )));
  }
  return Wrap(
      spacing: 5.0, // gap between adjacent chips
      runSpacing: 2.0, // gap between lines
      children: list);
}

After that call like this:

child: Row(children: <Widget>[
   listOfWidgets(itemList),
])

Conclusion:

In this article, We have been through how to Iterate through a List to Render a Multiple Widget In Flutter.

Keep Learning! Keep Fluttering! Drop us your valuable feedback to serve you better.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply