我正在尝试在 Flutter 中检索真实高度。我尝试了不同的选择:
MediaQuery.of(context).size.height * MediaQuery.of(context).devicePixelRatio
或
WidgetsBinding.instance.window.physicalSize.height
我在一个新的 Flutter 应用程序中添加了这两行(从头开始,只是 Flutter 创建的新计数器应用程序屏幕)
我也尝试使用全局密钥,但它不起作用(意思是我得到了相同的结果)。我正在三星 a10 上测试它,根据维基百科,它有一个 720 x 1520 pixels
。宽度我在计算时没有问题,但高度总是给我1424.0
。为什么我没有得到完整的高度?我正在使用更多手机型号。
答案 0 :(得分:0)
请参阅 physicalSize
属性的 documentation:
此值不考虑任何屏幕键盘或其他系统 UI。 padding 和 viewInsets 属性提供有关视图每一侧可能被系统 UI 遮挡的程度的信息。
答案 1 :(得分: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(context);
然后你可以调用ScreenUtil.screenHeight