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

查看:27
本文介绍了遍历列表以在 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 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.

推荐答案

基本上当你在一个函数上点击 '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天全站免登陆