【问题标题】:How can I get the screen size in Flutter without BuildContext?如何在没有 BuildContext 的情况下在 Flutter 中获取屏幕大小?
【发布时间】:2021-02-19 11:54:18
【问题描述】:

首先,this,虽然在 Question 中相似,但不是我需要的,因为 Answer 对我的情况没有帮助。

我让我的 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();
}

【问题讨论】:

  • WidgetsBinding.instance.window 呢?
  • @pskink 看起来像我需要的,但是 - 我将如何在这里使用它?
  • 检查Window类属性

标签: flutter dart


【解决方案1】:

为了将来参考完整的解决方案:

通过添加

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

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

【讨论】:

    猜你喜欢
    • 2020-01-05
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2020-02-23
    • 2011-10-18
    • 2013-03-13
    相关资源
    最近更新 更多