在没有BuildContext的情况下如何在Flutter中获取屏幕尺寸?

Mar*_* Ge 3 dart flutter

首先,虽然与问题类似,但不是我所需要的,因为答案对我的情况没有帮助。

我让我的 AppConfig 根据设备决定字体大小,以便非常大的设备(例如平板电脑)获得更大的文本(一点点)。我的配置在任何视图之前被调用,所以在运行时我没有 BuildContext。那么我该怎么做呢?

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();
}
Run Code Online (Sandbox Code Playgroud)

Mar*_* Ge 11

供将来参考,完整的解决方案:

通过增加

Size size = WidgetsBinding.instance.window.physicalSize;
double width = size.width;
double height = size.height;
Run Code Online (Sandbox Code Playgroud)

您可以在任何地方且无需 BuildContext,从设备屏幕获取尺寸。


小智 5

在这种情况下,您应该考虑 devicePixelRatio;

Size size = WidgetsBinding.instance.window.physicalSize;
double ratio = WidgetsBinding.instance.window.devicePixelRatio;
double width = size.width / ratio;
Run Code Online (Sandbox Code Playgroud)