0

我正在尝试在 Flutter 中检索真实高度。我尝试了不同的选择:

MediaQuery.of(context).size.height * MediaQuery.of(context).devicePixelRatio

或者

WidgetsBinding.instance.window.physicalSize.height

我在一个新的 Flutter 应用程序中添加了这两行(从头开始,只是 Flutter 创建的新计数器应用程序屏幕)

我也尝试使用全局密钥,但它不起作用(意味着我得到相同的结果)。我正在三星 a10 上测试它,根据维基百科,它有一个720 x 1520 pixels. 宽度我计算它没有问题,但高度总是给我1424.0。为什么我没有得到完整的高度?更多的手机型号正在发生在我身上。

4

2 回答 2

0

尝试使用这个实用程序类它给了我正确的结果

class ScreenUtil {
  static ScreenUtil instance = new ScreenUtil();

  int width;
  int height;
  bool allowFontScaling;

  static MediaQueryData _mediaQueryData;
  static double _screenWidth;
  static double _screenHeight;
  static double _screenHeightNoPadding;
  static double _pixelRatio;
  static double _statusBarHeight;
  static double _bottomBarHeight;
  static double _textScaleFactor;
  static Orientation _orientation;

  ScreenUtil({
    this.width = 1080,
    this.height = 1920,
    this.allowFontScaling = false,
  });

  static ScreenUtil getInstance() {
    return instance;
  }

  void init(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    _mediaQueryData = mediaQuery;
    _pixelRatio = mediaQuery.devicePixelRatio;
    _screenWidth = mediaQuery.size.width;
    _screenHeight = mediaQuery.size.height;
    _statusBarHeight = mediaQuery.padding.top;
    _bottomBarHeight = mediaQuery.padding.bottom;
    _textScaleFactor = mediaQuery.textScaleFactor;
    _orientation = mediaQuery.orientation;
    _screenHeightNoPadding =
        mediaQuery.size.height - _statusBarHeight - _bottomBarHeight;
  }

  static MediaQueryData get mediaQueryData => _mediaQueryData;

  static double get textScaleFactory => _textScaleFactor;

  static double get pixelRatio => _pixelRatio;

  static Orientation get orientation => _orientation;

  static double get screenWidth => _screenWidth;

  static double get screenHeight => _screenHeight;

  static double get screenWidthPx => _screenWidth * _pixelRatio;

  static double get screenHeightPx => _screenHeight * _pixelRatio;

  static double get screenHeightNoPadding => _screenHeightNoPadding;

  static double get statusBarHeight => _statusBarHeight * _pixelRatio;

  static double get bottomBarHeight => _bottomBarHeight * _pixelRatio;

  get scaleWidth => _screenWidth / instance.width;

  get scaleHeight => _screenHeight / instance.height;

  setWidth(int width) => width * scaleWidth;

  setHeight(int height) => height * scaleHeight;

  setSp(int fontSize) => allowFontScaling
      ? setWidth(fontSize)
      : setWidth(fontSize) / _textScaleFactor;



}

在您的构建方法中首先调用

ScreenUtil().init(上下文);

然后你可以打电话ScreenUtil.screenHeight

于 2021-04-20T13:20:42.797 回答
0

请参阅该属性的文档:physicalSize

此值不考虑任何屏幕键盘或其他系统 UI。paddingviewInsets属性提供了有关视图的每一侧有多少可能被系统 UI 遮挡的信息。

于 2021-04-20T13:10:26.007 回答