颤振的真实高度



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

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

WidgetsBinding.instance.window.physicalSize.height

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

我还尝试使用全局密钥,但它不起作用(这意味着我得到了相同的结果(。我正在三星a10上测试它,据维基百科报道,它有一个720 x 1520 pixels。宽度我计算它没有问题,但高度总是给我1424.0。为什么我没有达到全高?我的手机型号越来越多。

请参阅physicalSize属性的文档:

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

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

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

最新更新