I am having a Stack
with two child elements. The second element is some Text
and the first element is a Container
with some blue background color. I want to have the height of the Container
match the height of the Stack
given by the height of the Text
-Widget. And the width of my Container
should be set dynamically with a percentage of the width of the Stack
which also comes from the Text
widget.
In other words: I want to build a progress indicator, that I can set dynamically. Altough the width of my parent is not known before build-time. And this width should be givene by the text-child-widget.
How can I achieve that?
Stack(
alignment: Alignment.centerLeft,
clipBehavior: Clip.none,
children: [
Container(
width: 50,
height: 20,
color: const Color(0xffa0a4fc),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: Text(
"some text",
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 22,
),
),
),
)
2
Answers
you need to calculate text width :
full code for your reference :
Per the
Stack
documentation:So, using
FractionallySizedBox
insidePositioned
and then having theText
determine theStack
size would do the trick:See a demo on dartpad.dev
Using a
TextPainter
to calculate size ofStack
‘s contents is also correct solution for your case but it has some drawbacks:Text
(as in the demo above).Text
‘s size twice.