3

Firstly, this, though similiar in Question, is not what I need as the Answer does not help me in my case.

I have my AppConfig decide the fontsize, based on device, so that very big devices, such as Tablets, get bigger Texts (by a bit). My config gets called before any Views, so I have no BuildContext while this is running. So how can I do this?

class AppConfig {
  static AppConfig _instance;

  static AppConfig instance() {
    if (_instance == null) {
      _instance = AppConfig();
    }
    return _instance;
  }

// config stuff for colours and themes

double width = MediaQuery.of(context).size.width;

if (width > 500) { //arbitrary number I haven't decided yet
    initWithBigFonts();
} else {
    initWithSmallFonts();
}
Maritn Ge
  • 997
  • 8
  • 35

4 Answers4

11

For future reference the full solution to this:

By adding

Size size = WidgetsBinding.instance.window.physicalSize;
double width = size.width;
double height = size.height;

You can, from anywhere and without BuildContext, get the Size from the device screen.

Maritn Ge
  • 997
  • 8
  • 35
5

in this case, you should think about the devicePixelRatio;

Size size = WidgetsBinding.instance.window.physicalSize;
double ratio = WidgetsBinding.instance.window.devicePixelRatio;
double width = size.width / ratio;
Arthur Mao
  • 51
  • 1
  • 1
2

the "window" singleton has been deprecated as of v3.7.0-32.0.pre because "window" assumed that the app consists of a single view which is not the case anymore. You can use one of the following two options.

  • PlatformDispatcher.instance.views.first.physicalSize. or,
  • PlatformDispatcher.instance.implicitView?.physicalSize (nullable)

divide the physicalSize by the devicePixelRatio (PlatformDispatcher.instance.views.first.devicePixelRatio) to get the view size.

For more info, https://docs.flutter.dev/release/breaking-changes/window-singleton

M. Hagos
  • 119
  • 1
  • 2
  • 12
1

Size size = MediaQueryData.fromWindow(WidgetsBinding.instance.window).size;