Reputation: 838
I have the following code:
@override
Widget build(BuildContext context) => Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width,
color: Colors.green.withOpacity(0.3),
child: Container(
alignment: Alignment.center,
height: MediaQuery.of(context).size.height * 0.25,
color: Colors.red.withOpacity(0.3),
),
)
I expect to see a red rectangle taking half of the screen, and centered inside a green one taking one quarter of the screen. But instead the green one spans the entire half (same size as the red one).
Why is that happening? How could I get the expected result without using a Stack?
For more context I'm trying to work around the issue with GestureDetector not responding correctly after translation with a Transform widget: https://github.com/flutter/flutter/issues/27587
EDIT:
After a good night of sleep the solution to achieve the expected result came easily, I added some margin to the inner container as follow:
@override
Widget build(BuildContext context) => Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width,
color: Colors.green.withOpacity(0.3),
child: Container(
margin: EdgeInsets.symmetric(vertical: MediaQuery.of(context).size.height * 0.25 * 0.5),
color: Colors.red.withOpacity(0.3),
),
);
But I'm way more interested in understanding why the first code is not working as expected. I read the source code for the Container widget but I can't find any obvious cause. Does anyone know?
EDIT 2:
@Pablo Barrera Answers gave me the idea to try adding the alignment to the first container instead (which is the way it should be indeed).
It also makes the second container take the expected size, which is unexpected. Still curious to know if there is a logical explanation for this.
@override
Widget build(BuildContext context) => Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width,
alignment: Alignment.center,
color: Colors.green.withOpacity(0.3),
child: Container(
height: MediaQuery.of(context).size.height * 0.25,
color: Colors.red.withOpacity(0.3),
),
);
Upvotes: 0
Views: 206
Reputation: 10983
You could use Wrap widget like this:
@override
Widget build(BuildContext context) => Container(
alignment: Alignment.center,
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width,
color: Colors.green.withOpacity(0.3),
child: Wrap(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.25,
color: Colors.red.withOpacity(0.3),
),
],
)
)
Edit: When adding 'alignment: Alignment.center' to the root Container, behind the scenes it's wrapping it's child with an Align widget, so the Wrap widget wouldn't be necessary anymore because the child Container won't try to expand to fit the root Container
Upvotes: 1