Flutter屏幕适配组件flutter_screenutil

2025年06月13日 Flutter

屏幕适配组件 flutter_screenutil

屏幕适配组件

说明地址:https://pub.dev/packages/flutter_screenutil

中文文档:https://github.com/OpenFlutter/flutter_screenutil/blob/master/README_CN.md

安装

dependencies:
  flutter:
    sdk: flutter
  # 添加依赖
  flutter_screenutil: ^{latest version}

属性

属性类型默认值描述
designSizeSizeSize(360, 690)设计稿中设备的尺寸(单位随意,建议 dp,但在使用过程中必须保持一致)
deviceSizeSizenull物理设备的大小
builderWidget Function()Container()一般返回一个 MaterialApp 类型的 Function()
orientationOrientationportrait屏幕方向
splitScreenModeboolfalse支持分屏尺寸
minTextAdaptboolfalse是否根据宽度/高度中的最小值适配文字
contextBuildContextnull传入 context 会更灵敏的根据屏幕变化而改变
childWidgetnullbuilder 的一部分,其依赖项属性不使用该库
rebuildFactorFunctiondefault返回屏幕指标更改时是否重建。

初始化并设置适配尺寸及字体大小是否根据系统的“字体大小”辅助选项来进行缩放在使用之前请设置好设计稿的宽度和高度,传入设计稿的宽度和高度(单位随意,但在使用过程中必须保持一致) 一定要进行初始化(只需设置一次),以保证在每次使用之前设置好了适配尺寸:

配置

您必须在 app 中使用它一次

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'app/routes/app_pages.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; //引用

void main() {
  //配置入口
  runApp(ScreenUtilInit(
    designSize: const Size(1080, 2400),
    minTextAdapt: true,
    splitScreenMode: true,
    builder: (context, child) {
      return GetMaterialApp(
        title: "Application",
        initialRoute: AppPages.INITIAL,
        getPages: AppPages.routes,
      );
    },
  ));
}

基本使用

import 'package:flutter_screenutil/flutter_screenutil.dart';
//宽高
 Container(
   width: 1080.w,
   height: 590.h,
   color: Colors.pink,
 ),
SizedBox(
  height: 30.h,
),
//字号大小
 Text(
    '屏幕字体',
    style: TextStyle(fontSize: 32.sp),
  )

封装 flutter_screenutil

/lib/service/screenAdapter.dart

import 'package:flutter_screenutil/flutter_screenutil.dart';

class Screenadapter {
  static width(num v) {
    return v.w;
  }

  static height(num v) {
    return v.h;
  }

  static fontSize(num v) {
    return v.sp;
  }

  static getScreenWidth() {
    // return ScreenUtil().screenWidth;
    return 1.sw;
  }

  static getScreenHeight() {
    // return ScreenUtil().scaleHeight;
    return 1.sh;
  }

  static statusBarHeight() {
    return ScreenUtil().statusBarHeight;
  }
}

封装使用

import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../controllers/category_controller.dart';
import '../../../service/screenAdapter.dart';

class CategoryView extends GetView<CategoryController> {
  const CategoryView({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('CategoryView'),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          Container(
            width: Screenadapter.getScreenWidth(),
            height: Screenadapter.getScreenHeight(),
            color: Colors.black38,
          )
        ],
      ),
    );
  }
}
0%