MediaQuery.of(context).padding.top is returning 0.0 when I'm using it with appBar. Why is that?
Asked Answered
D

2

9

When I use MediaQuery.of(context).padding.top without the navBar in the widget tree then it returns me the actual true value.

Reloaded 1 of 529 libraries in 637ms.
I/flutter (31730): 24.0

But when I place the appBar into the widget tree then it returns me 0.0 only.

Reloaded 1 of 529 libraries in 764ms.
I/flutter (31730): 0.0

Can someone please help that why it is happening?

Dilettante answered 1/1, 2021 at 5:10 Comment(0)
E
4

From this property's docs:

If you consumed this padding (e.g. by building a widget that envelops or accounts for this padding in its layout in such a way that children are no longer exposed to this padding), you should remove this padding for subsequent descendants in the widget tree by inserting a new MediaQuery widget using the MediaQuery.removePadding factory.

As the top padding is accounted for by the navBar, it is no longer exposed to widgets below it.

Erasmo answered 1/1, 2021 at 8:57 Comment(2)
Thanks, I figured it out now. I can collect the status bar size by calculating it before adding the navBar into the widget tree. :)Dilettante
can you provide a code snippet?Serf
D
0

In my case, I passed the padding value. and I consumed the padding.top in my Page1.

  Widget build(BuildContext context) {
    final padding = MediaQuery.of(context).padding;
    return SafeArea(
      child: Scaffold(
        body: IndexedStack(
          children: [
            Page1(padding),
            Page2(),
            Page3(),
            Page4(),
          ],
        ),
Duckling answered 5/10, 2022 at 2:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.