MaterialApp(
...,
builder: (BuildContext builderContext, Widget? child) => Overlay(
initialEntries: <OverlayEntry>[
OverlayEntry(
builder: (BuildContext context) => AppLifecycleOverlay(),
)
],
),
)
class AppLifecycleOverlay extends StatefulWidget {
const AppLifecycleOverlay({Key? key}) : super(key: key);
@override
State<AppLifecycleOverlay> createState() => _AppLifecycleOverlayState();
}
class _AppLifecycleOverlayState extends State<AppLifecycleOverlay>
with WidgetsBindingObserver {
bool shouldBlur = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance?.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
setState(() {
shouldBlur = state == AppLifecycleState.inactive ||
state == AppLifecycleState.paused;
});
}
@override
Widget build(BuildContext context) {
if (shouldBlur) {
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 8, sigmaY: 8),
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.grey.shade200.withOpacity(0.5),
),
);
}
return Container();
}
}
// main.dart
return MaterialApp(
title: 'Some Awesome App',
// ...
home: FutureBuilder<SharedPreferences>(
future: SharedPreferences.getInstance(),
builder: (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {
switch(snapshot.connectionState) {
case ConnectionState.done:
return Stack(
children: [
HomeWidget(title: 'Some Awesome App', prefs: snapshot.data),
Overlay(initialEntries: [
OverlayEntry(builder: (BuildContext context) => const AppLifecycleOverlay()),
])
]
);
default:
return const Center(child: Text("Loading..."));
}
},
),
);
AppLifecycleState.inactive
来检测的。在 iOS 上可以工作,但在 Android 上无法工作。你有更好的检测方法吗? - jakub