Container size depending on his content (text)
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
Result when you have text so long that it goes over the bounds of maxWidth
, in this case height resizes automatically:
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"),
)
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")
),
)
Ozz
Updated on December 18, 2022Comments
-
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 about 3 yearsDid you try yourself can you show your code?
-
Ozz about 3 yearsYes 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 about 3 yearsThank you mate for taking the time to explain it clearly
-
man of knowledge about 3 yearsGlad to help <3