It's possible to get the Scaffold's body height and width?

Viewed 15092

I'm trying to set dynamic sizes to the widgets that I implement in my application, I'm currently using:

MediaQuery.of(context).size.width/height

which gives you the size of the screen, but I need the widgets to be based on the size of the scaffolding body and not the full screen

5 Answers

You can user a Builder for your Scaffold:

return Scaffold(
  appBar: AppBar(),
  body: Builder(
    builder: (context) {
      return Stack(
        children: <Widget>[

And then:

bodyHeight = MediaQuery.of(context).size.height - Scaffold.of(context).appBarMaxHeight

At least, I found the solution in that way.

Here is the how you can get Scaffold body height correctly

Firstly, get the AppBar height. You need to use variable for it.

var appBar = AppBar(
      title: Text('Testing'),
    );

Now, follow the below code [which is basically=> Total Height - AppBar's height - Padding present on the top(App status bar's height )]

final bodyHeight = MediaQuery.of(context).size.height -
                  -appBar.preferredSize.height -
                  MediaQuery.of(context).padding.top

How to use it? Let say you have Column with 2 child

Column(children: [
        Container(
          height: bodyHeight * 0.7,
          child: ...,
        ),
        Container(
          height: bodyHeight * 0.3,
          child: ...,
        ),
      ],
)

You could also subtract the height of the appbar from MediaQuery.of(context).size.height

Just simply do this to get the size (height in this case) of your Scaffold Body alone.

final fullHeight = MediaQuery.of(context).size.height;
final appBar = AppBar(); //Need to instantiate this here to get its size
final appBarHeight = appBar.preferredSize.height + MediaQuery.of(context).padding.top;
final scaffoldBodyHeight = fullHeight - appBarHeight;

Note: appBarHeight is the addition of the height of the appBar and the height of the device status bar.

scaffoldBodyHeight is the height of your scaffold body!

Related