如何实现类似Android原生的Flutter完美全屏(Edge to Edge)模式
如何在Flutter中实现完美的全屏(Edge to Edge)模式
问题说明
在Android原生中可轻松实现状态栏仅显示文字、图标,底部导航栏同理,同时保留应用自身颜色的全屏效果:
- 竖屏:状态栏、导航栏背景透明,图标文字清晰显示,应用颜色贯穿至屏幕边缘
- 横屏:效果与竖屏一致,无适配问题
但使用现有Flutter代码实现时,横屏模式下存在适配异常:竖屏效果正常,横屏时无法保持原生的完美全屏表现。当前使用的代码如下:
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( systemNavigationBarContrastEnforced: false, statusBarColor: Colors.transparent, systemNavigationBarColor: Colors.transparent, systemStatusBarContrastEnforced: false, ));
解决方案
1. 结合屏幕方向监听动态配置SystemUI
横屏时需重新适配UIOverlayStyle,确保图标文字与背景的对比度,同时保持透明效果。可通过WidgetsBindingObserver监听方向变化:
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver { @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _setupEdgeToEdge(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeMetrics() { super.didChangeMetrics(); _setupEdgeToEdge(); } void _setupEdgeToEdge() { final isLandscape = MediaQuery.of(context).orientation == Orientation.landscape; SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( statusBarColor: Colors.transparent, systemNavigationBarColor: Colors.transparent, statusBarIconBrightness: isLandscape ? Brightness.light : Brightness.light, // 可根据应用背景调整亮度 systemNavigationBarIconBrightness: isLandscape ? Brightness.light : Brightness.light, systemNavigationBarContrastEnforced: false, systemStatusBarContrastEnforced: false, )); } // ... 页面其他逻辑代码 }
2. 正确处理安全区域
使用SafeArea包裹核心内容,避免内容被状态栏、导航栏遮挡,但允许应用背景颜色贯穿至屏幕边缘:
@override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.yellow, // 应用自身主题颜色 body: SafeArea( left: false, right: false, top: false, bottom: false, maintainBottomViewPadding: true, child: Center( child: Text("完美全屏效果展示"), ), ), ); }
设置left/right/top/bottom为false让背景延伸到边缘,maintainBottomViewPadding确保横屏时导航栏的内边距适配正确。
3. API 34 适配细节
针对Android 14(API 34),需在原生配置中补充以下设置:
在android/app/src/main/res/values/styles.xml的主题中添加:
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar"> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> </style>
确保系统不会强制添加额外的背景层。
测试注意事项
请使用带设备框的挖孔屏设备(如Pixel 6a)模拟器测试,确保API版本为34。
内容的提问来源于stack exchange,提问作者Tien
相关产品推荐
相关产品推荐

