Flutter how to refactor list of widget

Viewed 1084

I'm trying to render widgets on Stack and there is enum and with that state I want to render different widgets except for background image like this. enter image description here.

Stack looks like this now

new Stack(
    children: <Widget>[
      new Image.network(
        'https://images.unsplash.com/photo-1536226078409-fb25e1ed23b9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=51ea5572bb7bbdf19e616f3550fccd9d&auto=format&fit=crop&w=500&q=60',
         fit: BoxFit.cover,
         height: MediaQuery.of(context).size.height,
         width: MediaQuery.of(context).size.width,
      ),
      // render widgets here.
    ],
  ),

Then I want to render based on the enum state. So, code would be like this.

 List<Widget> listOfWidget() {
    return [];
  }

 new Stack(
        children: <Widget>[
          new Image.network(
            'https://images.unsplash.com/photo-1536226078409-fb25e1ed23b9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=51ea5572bb7bbdf19e616f3550fccd9d&auto=format&fit=crop&w=500&q=60',
             fit: BoxFit.cover,
             height: MediaQuery.of(context).size.height,
             width: MediaQuery.of(context).size.width,
          ),
          listOfWidget(),
        ],
      ),

However error says

The element type 'List' can't be assigned to the list type 'Widget'.

I totally understand what's going on but I don't know how to fix this. How can I refactor this?

1 Answers

The children property in a Stack is a List<Widget>.

You give it a value of [Widget, List<Widget>] which is a list with heterogeneous elements (first is a Widget, second elements is a List). So your given value is not a List<Widget> like it is necessary but rather a List<dynamic>. The second element in your List<dynamic> is a List<Widget> which needs to be assigned to a Widget which is not possible, hence the error.

You can do something like this:

List<Widget> listOfWidget() {
    return [];
}

new Stack(
    children: <Widget>[
        [new Image.network(
        'https://images.unsplash.com/photo-1536226078409-fb25e1ed23b9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=51ea5572bb7bbdf19e616f3550fccd9d&auto=format&fit=crop&w=500&q=60',
            fit: BoxFit.cover,
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
        )],
        listOfWidget(),
    ].expand((list) => list).toList();,
),

Notice that you put the original image in an List as well. So basically this will flatten your list to create a final List<Widget>.

Related