Sizing a container to exact half the screen size in flutter
If you want the container's height to be the half of the available space, you can use LayoutBuilder widget. With LayoutBuilder widget, you can know inside the builder function what the max available width and height would be. The example usage in your case would be like this:
Scaffold(
appBar: AppBar(),
body: Align(
alignment: Alignment.topCenter,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Container(
height: constraints.maxHeight / 2,
width: MediaQuery.of(context).size.width / 2,
color: Colors.red,
);
},
),
),
);
The best way and simplest route to this and similar problems is simply by using FractionallySizedBox
widget ; e.g
FractionallySizedBox(
alignment: Alignment.topCenter,
widthFactor: 0.5,
child: Container(
height: 100,
),
),
This widget (FractionallySizedBox
) lets you build up your child
by specifying the fraction of the parent width (or height) which is available to the child
widget. After that , by specifying the alignment
, you can specify the manner the rest of the space would be allocated.
For more help on this widget , please visit the offical help page of this widget.