亲宝软件园·资讯

展开

详解Flutter桌面应用如何进行多分辨率适配

Karl_wei 人气:0

前言

通过此篇文章,你将了解到:

Flutter windows和Android桌面应用屏幕适配的解决方案;

屏幕适配的相关知识和原理;

flutter_screenutil的实现原理和缺陷。

Flutter桌面应用的开发过程中,势必需要适配不同尺寸的屏幕。我们的预期是在不同尺寸的设备上,用户的使用感观基本一致。 如:在个人pc上,应用与屏幕的高度比是2/3;那么到60寸的大设备上,应用的尺寸依然需要2/3比例。

屏幕适配的一些基础概念

假设我们需要展示一张800×800的图片,那么在160dpi的手机屏幕上,我们只要设置800×800px的宽高;

但在320dpi的屏幕上,由于每英寸的像素点翻倍了,为了用户的视觉感受一致,就需要将图片设置的宽高设为1600×1600px。这就是屏幕适配最基本的原理,我们开发中所用到的适配库,最基础的能力就是提供这层转换。

Flutter 移动端开发的通用做法

Flutter移动端的生态已经很完备,我们一般在开发过程中会使用flutter_screenutil这个插件。这是一个纯Dart的pub,阅读源码发现其做法也很简单粗暴。

extension SizeExtension on num {
  ///[ScreenUtil.setWidth]
  double get w => ScreenUtil().setWidth(this);
  ///[ScreenUtil.setHeight]
  double get h => ScreenUtil().setHeight(this);
  ......
)
double get screenHeight =>
    _context != null ? MediaQuery.of(_context!).size.height : _screenHeight;
double setHeight(num height) => height * scaleHeight;
// 高度的缩放比:设备的逻辑像素的高度/设计稿的高度
double get scaleHeight =>
    (_splitScreenMode ? max(screenHeight, 700) : screenHeight) /
    _uiSize.height;

逻辑像素screenHeight从哪来?

获取MediaQueryData的size,即应用窗口的分辨率

extension on MediaQueryData? {
  MediaQueryData? nonEmptySizeOrNull() {
    if (this?.size.isEmpty ?? true)
      return null;
    else
      return this;
  }
}
/// The size of the media in logical pixels (e.g, the size of the screen).
///
/// Logical pixels are roughly the same visual size across devices. Physical
/// pixels are the size of the actual hardware pixels on the device. The
/// number of physical pixels per logical pixel is described by the
/// [devicePixelRatio].
final Size size;

存在的问题

flutter_screenutil 这个库在移动端使用是完全没有问题的。手机尺寸虽说层出不穷,但是也遵循瘦长的长方形规则,最重要的是应用默认都是全屏的,那么上面第3点获取到的应用窗口高度screenHeight和设备的大小刚好是完全吻合的。从而计算出的缩放比(设计稿尺寸/设备的尺寸 = 缩放比值)是偏差不大的。
我们在Android的桌面应用中,这个库也可以支持各种设备。

然而在windows等桌面端却没那么简单:

通过实践我们也验证了flutter_screenutil在桌面端的适配基本不起作用,且还会造成不少问题,比如:第一次运行字体都会偏大;当有多个扩展屏的时候,主副屏切换有bug。

桌面端解决方案

一、需求分析

我们希望flutter开发出来的应用,在不同的设备中:

分析以上预期效果,可以提炼出一个原则:应用的尺寸必须跟屏幕的物理大小占比一致,与分辨率、像素密度、缩放比都没关系。

二、实现原理

由于Android端用了flutter_screenutil这个库,Flutter又是跨平台的。为了降低开发成本,我试着fork源码下来更改,并且做了以下的操作:

// 文件路径:flutter_screenutil/lib/src/screenutil_init.dart
class ScreenUtilInit extends StatefulWidget {
  /// A helper widget that initializes [ScreenUtil]
  const ScreenUtilInit({
    Key? key,
    required this.builder,
    this.child,
    this.rebuildFactor = RebuildFactors.size,
    this.designSize = ScreenUtil.defaultSize,
    this.app2screenWithWidth = 1,
    this.splitScreenMode = false,
    this.minTextAdapt = false,
    this.useInheritedMediaQuery = false,
  }) : super(key: key);
  final ScreenUtilInitBuilder builder;
  final Widget? child;
  final bool splitScreenMode;
  final bool minTextAdapt;
  final bool useInheritedMediaQuery;
  final RebuildFactor rebuildFactor;
  /// The [Size] of the device in the design draft, in dp
  final Size designSize;
  /// 适用于桌面应用,应用窗口宽度与设备屏幕宽度的比例
  final double app2screenWithWidth;
  @override
  State<ScreenUtilInit> createState() => _ScreenUtilInitState();
}
dependencies:
  flutter:
    sdk: flutter
  # 获取屏幕物理参数
  screen_retriever: ^0.1.2
// 文件路径:flutter_screenutil/lib/src/screen_util.dart
/// Initializing the library.
static Future<void> init(
  BuildContext context, {
  Size designSize = defaultSize,
  double app2screenWithWidth = 1,
  bool splitScreenMode = false,
  bool minTextAdapt = false,
}) async {
  final navigatorContext = Navigator.maybeOf(context)?.context as Element?;
  final mediaQueryContext =
      navigatorContext?.getElementForInheritedWidgetOfExactType<MediaQuery>();
  final initCompleter = Completer<void>();
  WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((_) {
    mediaQueryContext?.visitChildElements((el) => _instance._context = el);
    if (_instance._context != null) initCompleter.complete();
  });
  // ** 我修改的代码 **
  Orientation orientation = Orientation.landscape;
  Size deviceSize = Size.zero;
  if (isDesktop) {
    Display primaryDisplay = await screenRetriever.getPrimaryDisplay();
    deviceSize = primaryDisplay.size;
    orientation = deviceSize.width > deviceSize.height
        ? Orientation.landscape
        : Orientation.portrait;
  } else {
    final deviceData = MediaQuery.maybeOf(context).nonEmptySizeOrNull();
    deviceSize = deviceData?.size ?? designSize;
    orientation = deviceData?.orientation ??
        (deviceSize.width > deviceSize.height
            ? Orientation.landscape
            : Orientation.portrait);
  }
  _instance
    .._context = context
    .._uiSize = designSize
    .._splitScreenMode = splitScreenMode
    .._minTextAdapt = minTextAdapt
    .._orientation = orientation
    .._screenWidth = deviceSize.width
    .._screenHeight = deviceSize.height;
  // 桌面区分设置下窗口大小
  if (isDesktop) {
    double appWidth = deviceSize.width * app2screenWithWidth;
    double appHeight = appWidth / (designSize.width / designSize.height);
    _instance._uiSize = Size(appWidth, appHeight);
  }
  _instance._elementsToRebuild?.forEach((el) => el.markNeedsBuild());
  return initCompleter.future;
}
extension SizeExtension on num {
  ///[ScreenUtil.setWidth]
  double get w => ScreenUtil().setWidth(this);
  ///[ScreenUtil.setHeight]
  double get h => ScreenUtil().setHeight(this);
  ///[ScreenUtil.radius]
  double get r => ScreenUtil().radius(this);
  ///[ScreenUtil.setSp]
  double get sp => ScreenUtil().setSp(this);
  ///smart size :  it check your value - if it is bigger than your value it will set your value
  ///for example, you have set 16.sm() , if for your screen 16.sp() is bigger than 16 , then it will set 16 not 16.sp()
  ///I think that it is good for save size balance on big sizes of screen
  double get sm => min(toDouble(), sp);
  ///屏幕宽度的倍数
  ///Multiple of screen width
  double get sw => ScreenUtil().screenWidth * this;
  ///屏幕高度的倍数
  ///Multiple of screen height
  double get sh => ScreenUtil().screenHeight * this;
  ///[ScreenUtil.setHeight]
  Widget get verticalSpace => ScreenUtil().setVerticalSpacing(this);
  ///[ScreenUtil.setVerticalSpacingFromWidth]
  Widget get verticalSpaceFromWidth =>
      ScreenUtil().setVerticalSpacingFromWidth(this);
  ///[ScreenUtil.setWidth]
  Widget get horizontalSpace => ScreenUtil().setHorizontalSpacing(this);
  ///[ScreenUtil.radius]
  Widget get horizontalSpaceRadius =>
      ScreenUtil().setHorizontalSpacingRadius(this);
  ///[ScreenUtil.radius]
  Widget get verticalSpacingRadius =>
      ScreenUtil().setVerticalSpacingRadius(this);
}

写在最后

以上方案,我在demo项目中验证过是没有问题的。接下来我希望能跟作者沟通下这个方案,看能否提pr合并进去。不然以后就没办法很轻松的享受到flutter_screenutil的更新迭代了。

期待Flutter桌面社区越来越丰富!更多关于Flutter桌面应用多分辨率适配的资料请关注其它相关文章!

加载全部内容

相关教程
猜你喜欢
用户评论