IT之家

Flutter 学习 之 flutter_screenutil

2022-04-03  本文已影响0人  半城半离人

本来以为Flutter的屏幕适配会挺完美之前就没关心过,为了解决设计图和需要的数字之间转换问题,所以才加上了此插件
官方文档地址 flutter_screenutil

一.插件的引用

在 pubspec.yaml 文件下新增 flutter_screenutil (注意空格问题)

dependencies:
  flutter_screenutil: ^5.3.1

二.创建ScreenHelper

之所以在插件上再封装是以后如果需要替换插件的时候只需要替换实现即可

import 'package:flutter_screenutil/flutter_screenutil.dart';

///屏幕缩放插件
class ScreenHelper {
///静态初始化方法
  static int(BuildContext context) {
    ScreenUtil.init(
        BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height),
        designSize:Size(375, 812),//这里传入你蓝湖等上面设计图的大小
        context: context,//老版本可能不用传这个 新版本这个必传 要不然会报问题
        orientation: Orientation.portrait);
  }

  static double get divider => height(2);

  /// 页面内边距
  static EdgeInsetsGeometry get pagePadding {
    return EdgeInsets.symmetric(
      horizontal: pageHorizontalPadding(),
      vertical: pageVerticalPadding(),
    );
  }

  /// 页面水平内边距
  static pageHorizontalPadding() => width(30);

  /// 页面垂直内边距
  static pageVerticalPadding() => width(20);

  ///列表item水平内边距
  static listHorizontalPadding() => width(20);

  ///列表item垂直内边距
  static listVerticalPadding() => width(30);

  /// 获取 计算后的字体
  static sp(double v, {bool allowFontScalingSelf = false}) {
    return v.sp;
  }

  /// 获取 计算后的高度
  static height(double value) {
    return value.h;
  }

  /// 获取 计算后的宽度
  static width(double value) {
    return value.w;
  }

  /// 获取 计算后的屏幕高度
  static double get screenHeight {
    return 1.sh;
  }

  /// 获取 计算后的屏幕高度
  static double get screenWidth {
    return 1.sw;
  }

  static double? get scale {
    return ScreenUtil().pixelRatio;
  }

  static double get textScaleFactor {
    return ScreenUtil().textScaleFactor;
  }

  ///顶部导航栏高度= 状态栏高度 + Appbar高度
  static double get TopBarHeight {
    return ScreenUtil().statusBarHeight + kToolbarHeight;
  }

  static double get topSafeHeight {
    return ScreenUtil().statusBarHeight;
  }

  static double get bottomSafeHeight {
    return ScreenUtil().bottomBarHeight;
  }
}

三.插件初始化

官方文档给了两种初始化方案,

///在你第一个跳转的页面的build中加入即可
    ScreenHelper.int(context);

四.插件的使用

//因为上面定义的都是静态方法所以直接
ScreenHelper.width(数字);
ScreenHelper.height(数字);
//上面有定义过一个页面边距,也可以这么用
Padding(padding: ScreenHelper.pagePadding);

五.注意事项

  1. 初始化最好是在MaterialApp下的第一个flutter页面页面初始化,否则调用的时候可能会报错
  2. 第二种方式 不支持在MaterialApp的theme的textTheme中使用字体适配
  3. 屏幕适配时候为了保证统一 一般只选择按一种方式适配
//按宽度适配
     SizedBox(width: ScreenHelper.width(20),height: ScreenHelper.width(20),)
///按高度适配 好处是和设计图看起来的组件高度一致
     SizedBox(width: ScreenHelper.height(20),height: ScreenHelper.height(20),)
///如果混着适配大概率你是得不到正方形的 宽度高度基本上不会相等(正方形屏幕除外)
     SizedBox(width: ScreenHelper.width(20),height: ScreenHelper.height(20),)
上一篇 下一篇

猜你喜欢

热点阅读