Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a list of widgets in Flutter

Tags:

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. How could I fix it and return as many widget as I want without creating another column inside the map?

like image 871
Dani Avatar asked Dec 15 '25 15:12

Dani


1 Answers

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.

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>. This can be achieved with the Iterable.expand() with an identity function.

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!

like image 187
fvillalba Avatar answered Dec 17 '25 14:12

fvillalba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!