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.
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With