Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a list to render multiple widgets in Flutter?

I have a list of strings defined like this:

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

I want to render the values on the screen side by side using text widgets. I have attempted to use the following code to attempt this:

for (var name in list) {    return new Text(name); } 

However, when I run this code, the for loop only runs once and there is only one text widget that gets rendered that says one (the first item in the list). Additionally, when I add a log message inside my for loop, it gets triggered once as well. Why isn't my for loop looping based on the length of the list? It seems to run only once and then quit.

like image 570
rakeshdas Avatar asked May 21 '18 02:05

rakeshdas


1 Answers

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 children of a widget

you can do something like this:

  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);   } 

or even better, you can use .map() operator and do something like this:

  Widget getTextWidgets(List<String> strings)   {     return new Row(children: strings.map((item) => new Text(item)).toList());   } 
like image 130
Rizky Andriawan Avatar answered Sep 21 '22 21:09

Rizky Andriawan