欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

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

来源: 开发者 投稿于  被查看 47029 次 评论:234

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


目录
  • 前言
  • 屏幕适配的一些基础概念
  • Flutter 移动端开发的通用做法
  • 存在的问题
  • 桌面端解决方案
    • 一、需求分析
    • 二、实现原理
  • 写在最后

    前言

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

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

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

    flutter_screenutil的实现原理和缺陷。

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

    屏幕适配的一些基础概念

    • 屏幕尺寸:屏幕的实际大小,主要看屏幕的对角线的长度,如:6.6英寸。
    • 分辨率:屏幕上像素点的总和,如:2400×1176。设备的屏幕其实是由N个像素格子组合成的,屏幕上显示的所有元素(图片、文字)从微观上都是为特定的像素格子绘制上内容。
    • 屏幕密度(dpi):每英寸的像素格子数。每英寸展示160个像素时称为一倍素;120个称为低倍素...

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

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

    Flutter 移动端开发的通用做法

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

    • 根据传入的设计稿尺寸,与设备的逻辑像素尺寸的比值作为缩放倍数
    • 开发者设置的尺寸都会去乘以对应的缩放倍数,从而实现widget大小的转换。
    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等桌面端却没那么简单:

    • 首先桌面设备的尺寸层出不穷,从个人笔记本到演示厅的屏幕,物理大小就已经差了几十倍,而像素密度却差别不大,这在适配上本身就存在更大难度。
    • 且通过验证,FlutterMediaQueryData获取的是应用窗口的大小,但是桌面设备屏幕大小跟应用窗口大小可不是一样大的,这就是最大的问题所在!

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

    桌面端解决方案

    一、需求分析

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

    • 应用的大小占比屏幕物理尺寸的比例是一致的;
    • 系统显示设置中的的缩放倍数不会影响应用的大小;
    • 资源大小可以进行适配,让图片等资源在不同尺寸的设备上都能显示清晰。

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

    二、实现原理

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

    • 在构造函数上,我加了一个参数app2screenWithWidth,让用户告知应用窗口宽度与屏幕宽度的比值,如:70%传入0.7;
    // 文件路径: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();
    }
    
    • yaml中引入 screenRetriever,获取到真实的设备屏幕像素,这个是真实的屏幕像素,跟应用窗口没关系;然后可以计算出应用窗口的大小,得出转换系数;
    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;
    }
    
    • 之后setWidth等方法都不需要懂了,因为都是拿上面的转换系数去计算的,系数对了转换自然就准确了。同时开发过程中也不需要做任何区分,该用.w的就用.w。我们看下.w等是如何通过扩展巧妙的把setWidth这些接口 做的轻量的。
    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);
    }
    
    • 资源适配,定义三个设备类型:大、中、小级别;然后在asset目录下区分三套资源,命名规范区分下larger、medium、small即可。
    • 这个做法非常硬核,我目前也没这个需求(O(∩_∩)O~。后续考虑渠道编译,减少包体积,同时开发时也不用区分名称。

    写在最后

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

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

    您可能感兴趣的文章:
    • Android studio 切换flutterSDK之后报错及解决办法(推荐)
    • android studio 3.6.1升级后如何处理 flutter问题
    • js 交互在Flutter 中使用 webview_flutter
    • Flutter Android多窗口方案落地实战
    • flutter升级3.7.3报错Unable to find bundled Java version解决

    用户评论