Flutter屏幕缩放管理插件flutter_screen_scaling的使用

Flutter屏幕缩放管理插件flutter_screen_scaling的使用

flutter_screen_scaling

pub package

一个用于适应不同比例屏幕和字体大小的Flutter插件。最初是从flutter_screenutil分支而来并做了一些美化更改。

中文文档

gitee

更新日志

使用

添加依赖

请在安装前检查最新版本。如果新版本有问题,请使用旧版本。

dependencies:
  flutter:
    sdk: flutter
 
  flutter_screen_scaling: ^2.3.0

导入到Dart代码中

import 'package:flutter_screen_scaling/flutter_screen_scaling.dart';

属性

属性 类型 默认值 描述
width double 1080px 设计稿中的设备宽度(单位为px)
height double 1920px 设计稿中的设备高度(单位为px)
allowFontScaling bool false 是否根据系统的“字体大小”辅助选项来缩放字体

初始化并设置适配尺寸及字体大小

在使用之前,请先设置设计稿的宽度和高度(单位为px)。务必在MaterialApp的home/initialRoute(即入口文件)中设置一次,以确保每次使用时都设置了适配尺寸:

// 填写设计稿中的屏幕尺寸

// 默认值 : 宽度 : 1080px , 高度:1920px , 允许字体缩放: false
ScreenUtil.init(context);

// 如果设计基于iPhone6尺寸(iPhone6 750*1334)
ScreenUtil.init(context, width: 750, height: 1334);

// 如果希望字体大小随系统字体大小辅助选项进行缩放
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);

使用方法

API

传递设计稿的像素大小
ScreenUtil().setWidth(540)  // 适应屏幕宽度
ScreenUtil().setHeight(200) // 适应屏幕高度
ScreenUtil().setSp(24)      // 适配字体
ScreenUtil().setSp(24, allowFontScalingSelf: true) // 适配字体(字体将遵循文本大小辅助设置)
ScreenUtil().setSp(24, allowFontScalingSelf: false) // 适配字体(字体不会遵循文本大小辅助设置)

ScreenUtil.pixelRatio       // 设备像素密度
ScreenUtil.screenWidth      // 设备宽度
ScreenUtil.screenHeight     // 设备高度
ScreenUtil.bottomBarHeight  // 底部安全区域距离,适用于全屏按钮
ScreenUtil.statusBarHeight  // 状态栏高度,刘海屏会更高(单位为px)
ScreenUtil.textScaleFactor  // 系统字体缩放因子

ScreenUtil().scaleWidth     // 实际宽度dp与设计稿px的比例
ScreenUtil().scaleHeight    // 实际高度dp与设计稿px的比例

0.2.wp  // 0.2倍屏幕宽度
0.5.hp  // 50%屏幕宽度
适配屏幕尺寸

传递设计稿的像素大小:

// 适应屏幕宽度: `ScreenUtil().setWidth(540)`
// 适应屏幕高度: `ScreenUtil().setHeight(200)`

// 如果您的dart sdk >= 2.6,您可以使用扩展函数:
// 替换以下代码:
Container(
  width: ScreenUtil().setWidth(50),
  height: ScreenUtil().setHeight(200),
)

// 可以使用以下方式:
Container(
  width: 50.w,
  height: 200.h,
)

// 注意
// 高度也会根据setWidth进行调整,以确保不发生变形(当需要正方形时)
// setHeight方法主要用于高度调整,当需要控制UI上的高度和实际显示的一致性时使用。
适配字体
// 传入字体大小,单位为像素,字体不会遵循文本大小辅助设置
// (初始化ScreenUtil时允许字体缩放)
ScreenUtil().setSp(28)    

// 传入字体大小,单位为像素,字体将遵循文本大小辅助设置
// (如果某个地方不遵循全局的allowFontScaling设置)
ScreenUtil().setSp(24, allowFontScalingSelf: true)

示例代码

import 'package:flutter/material.dart';
import 'package:flutter_screen_scaling/flutter_screen_scaling.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter_ScreenUtil',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    // 设置适配尺寸(填写设计稿中的屏幕尺寸)
    // 如果设计基于iPhone6尺寸(iPhone6 750*1334)
    ScreenUtil.init(width: 750, height: 1334, allowFontScaling: false);

    return ExampleWidget(title: 'FlutterScreenUtil Demo');
  }
}

class ExampleWidget extends StatefulWidget {
  const ExampleWidget({Key key, this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  _ExampleWidgetState createState() => _ExampleWidgetState();
}

class _ExampleWidgetState extends State<ExampleWidget> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    printScreenInformation();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                  width: ScreenUtil().setWidth(375),
                  height: ScreenUtil().setHeight(200),
                  color: Colors.red,
                  child: Text(
                    'My width:${ScreenUtil().setWidth(375)}dp \n'
                    'My height:${ScreenUtil().setHeight(200)}dp',
                    style: TextStyle(
                        color: Colors.white, fontSize: ScreenUtil().setSp(24)),
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                  width: ScreenUtil().setWidth(375),
                  height: ScreenUtil().setHeight(200),
                  color: Colors.blue,
                  child: Text(
                      'My width:${ScreenUtil().setWidth(375)}dp \n'
                      'My height:${ScreenUtil().setHeight(200)}dp',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil().setSp(24))),
                ),
              ],
            ),
            Text('Device width:${ScreenUtil.screenWidth}dp'),
            Text('Device height:${ScreenUtil.screenHeight}dp'),
            Text('Device width:${ScreenUtil.screenWidthPx}px'),
            Text('Device height:${ScreenUtil.screenHeightPx}px'),
            Text('Device pixel density:${ScreenUtil.pixelRatio}'),
            Text('Bottom safe zone distance:${ScreenUtil.bottomBarHeight}dp'),
            Text('Status bar height:${ScreenUtil.statusBarHeight}dp'),
            Text(
              'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}',
              textAlign: TextAlign.center,
            ),
            Text(
              'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}',
              textAlign: TextAlign.center,
            ),
            SizedBox(
              height: ScreenUtil().setHeight(100),
            ),
            Text('System font scaling factor:${ScreenUtil.textScaleFactor}'),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                    'My font size is 24px on the design draft and will not change with the system.',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: ScreenUtil().setSp(24),
                    )),
                Text(
                    'My font size is 24px on the design draft and will change with the system.',
                    style: TextStyle(
                        color: Colors.black,
                        fontSize: ScreenUtil()
                            .setSp(24, allowFontScalingSelf: true))),
              ],
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.title),
        onPressed: () {
          ScreenUtil.init(width: 1500, height: 1334, allowFontScaling: false);
          setState(() {});
        },
      ),
    );
  }

  void printScreenInformation() {
    print('Device width dp:${ScreenUtil.screenWidth}'); // 设备宽度
    print('Device height dp:${ScreenUtil.screenHeight}'); // 设备高度
    print(
        'Device pixel density:${ScreenUtil.pixelRatio}'); // 设备像素密度
    print(
        'Bottom safe zone distance dp:${ScreenUtil.bottomBarHeight}'); // 底部安全区域距离,适合全屏按钮
    print(
        'Status bar height dp:${ScreenUtil.statusBarHeight}dp'); // 状态栏高度,刘海屏会更高 单位dp
    print(
        'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}');
    print(
        'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}');
    print(
        'The ratio of font and width to the size of the design:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
    print(
        'The ratio of  height width to the size of the design:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
  }
}

更多关于Flutter屏幕缩放管理插件flutter_screen_scaling的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter屏幕缩放管理插件flutter_screen_scaling的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_screen_scaling 是一个用于在 Flutter 应用中管理屏幕缩放的插件,它可以帮助开发者在不同屏幕尺寸的设备上保持一致的 UI 布局和比例。通过这个插件,你可以轻松地根据屏幕的宽度和高度来缩放 UI 元素,从而确保应用在各种设备上都能有良好的显示效果。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 flutter_screen_scaling 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_screen_scaling: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

基本用法

  1. 初始化插件

    在你的应用的 main.dart 文件中,初始化 flutter_screen_scaling 插件。通常你会在 main() 函数中完成这个操作。

    import 'package:flutter/material.dart';
    import 'package:flutter_screen_scaling/flutter_screen_scaling.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Screen Scaling Example',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: ScreenScaling(
            builder: (context) => HomePage(),
          ),
        );
      }
    }
    
  2. 使用缩放功能

    ScreenScalingbuilder 中,你可以使用提供的 context 来访问缩放相关的功能。例如,你可以使用 context.scaleWidthcontext.scaleHeight 来根据屏幕尺寸缩放 UI 元素。

    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter Screen Scaling Example'),
          ),
          body: Center(
            child: Container(
              width: context.scaleWidth(200),  // 根据屏幕宽度缩放
              height: context.scaleHeight(100), // 根据屏幕高度缩放
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Hello, World!',
                  style: TextStyle(
                    fontSize: context.scaleText(20), // 根据屏幕尺寸缩放文本大小
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }
回到顶部