Sie Ivan Siehoyono
Sie Ivan Siehoyono

Reputation: 70

Flutter : How to set container size to wrap_content in Wrap widget

I want to set Container size to wrap_content instead of it taking the whole screen width. I can get the wrap_content size by changing Wrap widget with Row, but it will overflow if the children widget is bigger than the screen.

Below is the code I use with Wrap widget

@override
  Widget build(BuildContext context) {
    return Wrap(
      children: <Widget>[
        Container(
          height: 100.0,
          color: Colors.lightGreenAccent,
          child: const Center(
            child: Text('Container 1'),
          ),
        ),
        Container(
          height: 100.0,
          color: Colors.cyan,
          child: Center(
            child: Text('Container 2'),
          ),
        ),
      ],
    );
  }

I get this result with Wrap widget

With Wrap widget

When I change it to Row instead of Wrap, I get this result With Row widget

How can I achieve this using Wrap widget? Or is there any other widget similar to Wrap where the overflowed widget will automatically build into a new line?

Upvotes: 2

Views: 7775

Answers (2)

Luwx
Luwx

Reputation: 160

Wrap the containers with an UnconstrainedBox widget, this way the container will be free to size itself to its children’s size.

Upvotes: 16

Nisanth Reddy
Nisanth Reddy

Reputation: 6405

One way to achieve this would be to use the Column widget as your Text parent. Then give mainAxisAlignment: MainAxisAlignment.center to center your Text.

Container(
  height: 100.0,
  color: Colors.lightGreenAccent,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Text('Container 1'),
    ],
  ),
),

enter image description here

Upvotes: 3

Related Questions