Home > other >  Manage Device Sizes MediaQuery Globally
Manage Device Sizes MediaQuery Globally

Time:08-09

What is the proper way to handle device size globally. The idea is not to have a [MediaQuery.of(context).size.width] on each screen of the app. There is already a question and answer about it, but the only answer is out of date because there was no null safety yet.

The answer suggests creating a constants.dart file, like in the image below:

1

And initialize in the build of the first widget of the application:

2

The problem is that for it to be constant it must have a value, and not wait for the first build. It is also true that the value canchange based on device orientation and I would like to handle this as well.

I have doubts about it. if someone can help me

CodePudding user response:

You cannot save the screen dimensions as a constant, because they will change if the device is rotated, or when the screen is resized, such as for desktop and web apps.

Instead you should be pushing your cutpoint decisions as low as possible, using LayoutBuilder.

LayoutBuilder seems preferable over every use of MediaQuery for sizing a viewport (either the whole screen, or the space left in a column or other layout).

LayoutBuilder also works hard to avoid rebuilding its child if the size doesn't change and the parents haven't had to re-layout.

The builder function is called in the following situations:

  • The first time the widget is laid out.
  • When the parent widget passes different layout constraints.
  • When the parent widget updates this widget.
  • When the dependencies that the builder function subscribes to change.

The builder function is not called during layout if the parent passes the same constraints repeatedly.

And you don't have to think about "the height of the appbar" ever again, because you're getting the space left, not the total space on the screen.

Check it out: https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html

  • Related