Jozott
Jozott

Reputation: 2674

Flutter - Wrap Row of Expanded Widgets

I have a Row where the children are Expanded widgets. My goal is to wrap this Row (like with Wrap) if there is not enough space for all children.

I already tried to replace Row by Wrap:

return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Wrap(
          children: [
            Expanded(
              child: element("Sun Glasses"),
            ),
          ],
        )
      ),
    );

but this lead to the error:

The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.

The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type WrapParentData.

Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a Wrap widget.

Since it is important that the elements of a row fill it up, I cannot simply remove Expanded. Is there a way to achieve this?

This is the Mockup that I am trying to implement:

enter image description here

Upvotes: 5

Views: 7348

Answers (1)

Jozott
Jozott

Reputation: 2674

Since I couldn't find any existing solution for this problem, I wrote a custom RenderBox widget.

You can find the source code on Github and the flutter package on pub.dev.

Simple Example with FlexList

SizedBox(
    width: 300,
    child: FlexList(
      horizontalSpacing: 5,
      verticalSpacing: 10,
      children: [
        for (var i = 0; i < 10; i++)
          Container(
            color: Theme
                .of(context)
                .backgroundColor,
            padding: EdgeInsets.symmetric(
                horizontal: 20 + 20 * (i % 4), vertical: 10),
            child: Text("Item $i"),
          )
      ],
    )),

Example Rendering

Upvotes: 13

Related Questions