Container size depending on his content (text)

924

You need to not assign width or height to the Container so it will resize depending on the child:


Container(
     color: Colors.red,
     child: const Text("Hi there111"),
)

If you want to control max width and max height you will use Container's constraints field


Container(
      color: Colors.red,
      constraints: const BoxConstraints(
          maxWidth: 200,
      ),
      child: const Text("Hi there11122222222"),
)

And of course you can give it minWidth and minHeight in BoxConstraints.

Result when you are under maxWidth

enter image description here

Result when you have text so long that it goes over the bounds of maxWidth, in this case height resizes automatically:

enter image description here

You can also add padding for better look:


Container(
    padding: EdgeInsets.all(20),
    color: Colors.red,
    constraints: const BoxConstraints(
      maxWidth: 200,
    ),
    child: const Text("Hi there11122222222222222222"),
)

enter image description here

But for other types of widgets, other than Text it will be much safer if you wrap them with FittedBox like this, notice the Text widget :


Container(
    padding: EdgeInsets.all(20),
    color: Colors.red,
    constraints: const BoxConstraints(
      maxWidth: 200,
    ),
    child: FittedBox(
       fit: BoxFit.fill,
       child: const Text("asfasfasfasfasf")
    ),

)

Share:
924
Ozz
Author by

Ozz

Updated on December 18, 2022

Comments

  • Ozz
    Ozz over 1 year

    I want my container to have different size depending on their content (in this case a text), if one user write a longer text the container will be biger and if another user write a shorter text the container will be smaller.

    Is it possible? And if not is there another way to do it?

    Thanks

    This is what I want to achieve (it's a screenshot of Samsung note app)

    • Chirag Bargoojar
      Chirag Bargoojar about 3 years
      Did you try yourself can you show your code?
    • Ozz
      Ozz about 3 years
      Yes I tried to do it multiple time but it's always end up in a failure, but it's finally working thanks to the answer down below.
  • Ozz
    Ozz about 3 years
    Thank you mate for taking the time to explain it clearly
  • man of knowledge
    man of knowledge about 3 years
    Glad to help <3