Flutter中的flutter_screenutil是一个强大的屏幕适配插件,旨在帮助开发者确保应用在不同屏幕尺寸和分辨率的设备上保持合理的布局和尺寸。以下是使用flutter_screenutil进行屏幕适配的详细步骤和方法

1. 添加依赖

在项目的pubspec.yaml文件中添加flutter_screenutil依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_screenutil: ^5.6.1

然后运行flutter pub get来下载并安装该库。

2. 初始化ScreenUtil

在应用启动时初始化ScreenUtil,通常在MaterialApp的home页面中进行初始化。可以通过以下代码进行初始化:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(360, 690), // 设计稿的尺寸
      builder: () => MaterialApp(
        home: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter ScreenUtil Example'),
      ),
      body: Center(
        child: Container(
          width: ScreenUtil().setWidth(250), // 根据设计稿宽度适配
          height: ScreenUtil().setHeight(250), // 根据设计稿高度适配
          color: Colors.blue,
        ),
      ),
    );
  }
}

3. 使用ScreenUtil进行尺寸适配

在UI代码中,可以使用ScreenUtil提供的方法进行尺寸适配。例如:

  • setWidth(double width):根据设计稿宽度适配。
  • setHeight(double height):根据设计稿高度适配。
  • setSp(double size):根据设计稿字体大小适配。

示例代码如下:

Container(
  width: ScreenUtil().setWidth(250),
  height: ScreenUtil().setHeight(250),
  color: Colors.blue,
  child: Text(
    'Hello World',
    style: TextStyle(
      fontSize: ScreenUtil().setSp(16), // 根据设计稿字体大小适配
    ),
  ),
)

4. 字体适配

除了尺寸适配,ScreenUtil还支持字体大小的适配。可以通过setSp方法来设置字体大小,确保在不同设备上字体大小一致。

5. 获取屏幕信息

ScreenUtil提供了多种API来获取设备的屏幕信息,如屏幕宽度、高度、像素密度等。例如:

  • ScreenUtil().screenWidth:获取屏幕宽度。
  • ScreenUtil().screenHeight:获取屏幕高度。
  • ScreenUtil().pixelRatio:获取设备的像素密度。

6. 注意事项

  • 初始化ScreenUtil时,确保设计稿的尺寸与实际设备尺寸一致。
  • 在不同设备上测试应用,确保布局和字体大小适配正确。
  • 注意ScreenUtil并非万能解决方案,应结合其他布局技术使用。

更多推荐