如何实现Flutter应用非活跃状态下的模糊效果,类似iOS相机应用的表现
Flutter 应用非活跃状态模糊效果实现方案
该方案可实现和iOS系统相机进入后台时完全一致的模糊表现,无需引入复杂第三方依赖,同时支持iOS、Android双端适配。
实现步骤
1. 生命周期监听
通过WidgetsBindingObserver监听应用生命周期状态,触发模糊的时机和系统对齐:
- iOS端:在
AppLifecycleState.inactive状态触发,该状态会在应用即将进入后台、系统触发后台快照前调用,刚好可以在快照生成前覆盖模糊层 - Android端:在
AppLifecycleState.paused状态触发,对应应用完全进入后台的时机
2. 全局模糊层挂载
推荐在MaterialApp的builder参数中挂载模糊层,保证模糊层永远处于路由栈最顶层,不会被业务页面遮挡:
import 'dart:ui'; import 'package:flutter/material.dart'; class BlurBackgroundWrapper extends StatefulWidget { final Widget child; const BlurBackgroundWrapper({super.key, required this.child}); @override State<BlurBackgroundWrapper> createState() => _BlurBackgroundWrapperState(); } class _BlurBackgroundWrapperState extends State<BlurBackgroundWrapper> with WidgetsBindingObserver { AppLifecycleState _currentState = AppLifecycleState.resumed; // 模糊程度和iOS系统后台模糊对齐 final double _blurSigma = 11; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void didChangeAppLifecycleState(AppLifecycleState state) { super.didChangeAppLifecycleState(state); setState(() { _currentState = state; }); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } bool get _needBlur { if (Theme.of(context).platform == TargetPlatform.iOS) { return _currentState == AppLifecycleState.inactive || _currentState == AppLifecycleState.paused; } else { return _currentState == AppLifecycleState.paused; } } @override Widget build(BuildContext context) { return Stack( children: [ widget.child, if (_needBlur) BackdropFilter( filter: ImageFilter.blur(sigmaX: _blurSigma, sigmaY: _blurSigma), child: Container( color: Colors.black.withOpacity(0.1), // 可选:在模糊层上添加你的应用logo,和系统相机效果一致 // child: Center(child: Image.asset('assets/logo.png', width: 80)), ), ) ], ); } }
3. 全局注册
在MaterialApp的builder中注册上面的封装组件即可全局生效:
MaterialApp( title: '你的应用名称', builder: (context, child) { return BlurBackgroundWrapper(child: child!); }, home: const HomePage(), )
效果示意

注意事项
- 模糊参数
sigmaX、sigmaY建议设置在10~12区间,和iOS系统原生后台模糊的视觉效果对齐 - iOS端不要仅监听
paused状态,inactive状态的触发时机早于系统后台快照生成时机,可以避免后台快照泄漏隐私内容 - 如果需要部分页面不展示模糊,可以在
_needBlur判断中添加路由栈的判断逻辑即可
内容的提问来源于stack exchange,提问作者jakub
相关产品推荐
相关产品推荐

