实现Flutter Android挖孔屏铺满全屏的步骤
1. 确定项目依赖
在Flutter项目的pubspec.yaml
文件中,添加以下依赖:
dependencies:
flutter:
sdk: flutter
flutter_screenutil: ^5.0.0
notch_ear_phone: ^1.0.0
flutter_screenutil
用于适配不同分辨率的屏幕,notch_ear_phone
用于处理挖孔屏的相关问题。
2. 创建Flutter挖孔屏适配工具类
创建一个名为notch_screen_util.dart
的文件,并添加以下代码:
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class NotchScreenUtil {
static double getSafeWidth() {
double screenWidth = ScreenUtil().screenWidth;
double safeAreaWidth = screenWidth - ScreenUtil().screenSafeArea.left - ScreenUtil().screenSafeArea.right;
return safeAreaWidth;
}
}
上述代码定义了一个NotchScreenUtil
类,其中的getSafeWidth
方法用于获取安全区域的宽度。
3. 实现全屏铺满挖孔屏
在Flutter项目的主界面中,添加以下代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:notch_ear_phone/notch_ear_phone.dart';
import 'notch_screen_util.dart';
void main() {
// 设置Android状态栏和导航栏颜色为透明
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
systemNavigationBarColor: Colors.transparent,
));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 初始化屏幕适配工具
ScreenUtil.init(
designSize: Size(750, 1334), // 根据设计稿的宽高进行设置
allowFontScaling: false,
);
// 检测挖孔屏信息,以适配UI布局
NotchEarPhone.checkDeviceEarInfo().then((value) {
if (value == NotchEarPhoneDeviceEarInfo.hasEar) {
// 如果是挖孔屏设备,则设置铺满全屏
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
runApp(MyHomePage());
});
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter挖孔屏铺满全屏'),
),
body: Container(
width: NotchScreenUtil.getSafeWidth(),
child: Center(
child: Text(
'Hello World!',
style: TextStyle(
fontSize: 24.sp,
),
),
),
),
);
}
}
上述代码中,通过调用SystemChrome.setSystemUIOverlayStyle
方法将Android状态栏和导航栏的颜色设置为透明,以实现全屏效果。同时,调用ScreenUtil.init
方法初始化屏幕适配工具,并在NotchEarPhone.checkDeviceEarInfo
方法中检测是否为挖孔屏设备,如果是,则设置支持横竖屏。
4. 运行项目
在终端中运行以下命令,启动Flutter项目:
flutter run
现在,你的Flutter应用程序将适配挖孔屏,并铺满全屏。
甘特图
gantt
dateFormat DD-MM-YYYY
title Flutter挖孔屏铺满全屏的实现流程
section 创建项目依赖
添加依赖 : done, 01-10-2022, 1d
section 创建工具类
创建挖孔屏适配工具类 : done, 02-10-2022, 1d
section 实现挖孔屏铺满全屏
设置全屏 : done, 03-10-2022, 1d
编写界面布局 : done, 04-10-2022, 1d
section 运行项目
运行项目 : done, 05