Flutter提供了一个名为ScreenUtil的插件,用于进行屏幕的适配。以下是使用ScreenUtil进行全局适配的简单方法:
首先,在pubspec.yaml中添加依赖:
dependencies:
  flutter:
    sdk: flutter
  screenutil: ^0.0.1然后,在lib/main.dart中或者在需要使用ScreenUtil的文件中,初始化ScreenUtil:
import 'package:flutter/material.dart';
import 'package:screenutil/screenutil.dart';
 
void main() {
  // 设置设计稿宽度和高度,一般是按照iPhone6的尺寸设置
  ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(designSize);
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
      builder: (BuildContext context, Widget child) {
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(
            textScaleFactor: ScreenUtil.getScaleWidth(),
          ),
          child: child,
        );
      },
    );
  }
}
 
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter ScreenUtil Adapter'),
      ),
      body: Container(
        // 使用ScreenUtil进行适配
        width: ScreenUtil().setWidth(375), // 宽度设置为375个逻辑像素
        height: ScreenUtil().setHeight(200), // 高度设置为200个逻辑像素
        child: Text('Hello World!',
          style: TextStyle(
            fontSize: ScreenUtil().setSp(24), // 字体大小设置为24个逻辑像素
          ),
        ),
      ),
    );
  }
}在上述代码中,我们首先在main函数中初始化了ScreenUtil,并设置了设计稿的宽度和高度。然后在MyApp中通过builder属性重新构建MediaQuery,使得文字大小可以根据屏幕宽度自动调整。在HomePage中,我们使用ScreenUtil().setWidth()和ScreenUtil().setHeight()方法来设置组件的宽度和高度,使用ScreenUtil().setSp()来设置字体大小,从而实现了基本的全局适配功能。