Search code examples
flutterdartflutter-layoutword-wrap

Mastering flutter Wrap-Layout


I got a title and a description for some UI-element and want them to be placed among each other. The title and the description will vary from length. (as I don't know the length before build time)

This is my code:

Container(
  color: Colors.red,
  margin: EdgeInsets.all(0),
  padding: EdgeInsets.all(0),
  child: Wrap(
    direction: Axis.horizontal,
    children: [
      Padding(
        padding: EdgeInsets.only(top: 15, bottom: 0, left: 15, right: 15),
        child: Text(
          "this is a test title",
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.black),
        ),
      ),
      Padding(
          padding: EdgeInsets.only(top: 15, bottom: 15, left: 15, right: 15),
          child: Text(
            "This is a test descripton This is a test descripton This is a test descripton This is a test descripton",
            style: TextStyle(color: Colors.black, fontSize: 15),
          )),
    ],
  ))

It looks like this, which is what I want:

enter image description here

Also when the title and the description are long, it looks how I want it to look:

enter image description here

But when the title and the description are rather short, this happens:

enter image description here

They are now side-by-side which is not what I want. If I'd change the direction to Axis.verticalthis would happen:

enter image description here

Looks good right?

But what if the title and description are long again?

enter image description here

Damn, now the text just overflows on the side.

Has anyone an idea on how to achieve what I want, no matter the length of my title and description? Thanks a lot!


Solution

  • Wrap is the wrong widget for this task. To force widgets to display in a vertical arrangement like this, use a Column with MainAxisSize.min.

    Container(
      color: Colors.red,
      margin: EdgeInsets.all(0),
      padding: EdgeInsets.all(0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Padding(
            padding: EdgeInsets.only(top: 15, bottom: 0, left: 15, right: 15),
            child: Text(
              "this is a test title",
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 15, bottom: 15, left: 15, right: 15),
            child: Text(
              "This is a test descripton This is a test descripton This is a test descripton This is a test descripton",
              style: TextStyle(color: Colors.black, fontSize: 15),
            ),
          ),
        ],
      ),
    );