Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the screen size in Flutter without BuildContext?

Tags:

flutter

dart

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();
}
like image 916
Maritn Ge Avatar asked Feb 02 '26 21:02

Maritn Ge


1 Answers

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.

like image 183
Maritn Ge Avatar answered Feb 04 '26 13:02

Maritn Ge