遍历列表以在Flutter中渲染多个小部件? [英] Iterating through a list to render multiple widgets in Flutter?

查看:461
本文介绍了遍历列表以在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);
}

但是,当我运行这段代码时,for循环只运行一次只是一个呈现的文本小部件,其中显示 one (列表中的第一项)。另外,当我在for循环中添加一条日志消息时,它也会被触发一次。为什么我的for循环不是基于列表的长度?似乎只运行一次然后退出。

However, when I run this code, the for loop only runs once and there is only one text widget that get rendered which 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.

推荐答案

基本上,当您在某个函数上单击 return时,该函数将停止并不会继续您的迭代,因此您需要做的是将它们全部放在列表中,然后将其添加为小部件的子项

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

您可以执行以下操作:

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

甚至更好,您可以使用.map()运算符执行类似的操作

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

这篇关于遍历列表以在Flutter中渲染多个小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆