简体   繁体   English

返回 Flutter 中的小部件列表

[英]Return a list of widgets in Flutter

Column(
                children: <Widget>[
                  ...myObject
                      .map((data) => Text("Text 1"), Text("Text 2")),
                ]
);

This block of code will fail because I'm returning 2 widgets instead of one.这段代码会失败,因为我要返回 2 个小部件而不是一个。 How could I fix it and return as many widget as I want without creating another column inside the map?如何修复它并返回任意数量的小部件,而无需在地图内创建另一列?

First you cant use an arrow function to return multiple values, you need to change it to a normal function that returns a list of widgets.首先,您不能使用箭头函数返回多个值,您需要将其更改为返回小部件列表的普通函数。 Second, you need to use the .toList() method since .map is lazy and you need to iterate in order to map execute.其次,您需要使用 .toList() 方法,因为 .map 是惰性的,您需要迭代才能执行映射。

With this 2 steps you are going to end with a List<List<Widget>> and you should flat it before return it to a column that needs a List<Widget> .通过这 2 个步骤,您将以List<List<Widget>> ,您应该在将它返回到需要List<Widget>的列之前将其展平。 This can be achieved with the Iterable.expand() with an identity function.这可以通过带有标识函数的 Iterable.expand() 来实现。

You can try something like this:你可以尝试这样的事情:

                Column(
                  children: <Widget>[
                    ..._generateChildrens(myObjects),
                  ],
                ),

And the actual implementation to obtain the widgets is:获取小部件的实际实现是:

  List<Widget> _generateChildrens(List myObjects) {
    var list = myObjects.map<List<Widget>>(
      (data) {
        var widgetList = <Widget>[];
        widgetList.add(Text("Text 1"));
        widgetList.add(Text("Text 2"));
        return widgetList;
      },
    ).toList();
    var flat = list.expand((i) => i).toList();
    return flat;
  }

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM