Flutter BaseWidget 实现onResume、onPause()
在Flutter中,没有直接的生命周期回调像onResume
和onPause
。但是,你可以使用WidgetsBindingObserver
接口来监听生命周期事件。
以下是一个简单的示例,展示如何在Flutter中实现类似Android的onResume
和onPause
:
import 'package:flutter/material.dart';
class LifecycleWatcher extends StatefulWidget {
@override
_LifecycleWatcherState createState() => _LifecycleWatcherState();
}
class _LifecycleWatcherState extends State<LifecycleWatcher> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.resumed:
print('App is resumed');
// Handle onResume
break;
case AppLifecycleState.inactive:
print('App is inactive');
// Handle onPause
break;
case AppLifecycleState.paused:
print('App is paused');
// Handle onPause
break;
case AppLifecycleState.detached:
print('App is detached');
// Handle cleanup
WidgetsBinding.instance.removeObserver(this);
break;
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Lifecycle Watcher'),
),
);
}
}
在这个例子中,_LifecycleWatcherState
类通过with WidgetsBindingObserver
来扩展WidgetsBindingObserver
接口。然后,它实现了didChangeAppLifecycleState
方法来响应生命周期状态的变化。这里,resumed
状态被视为onResume
,而inactive
和paused
状态被视为onPause
。记得在dispose
方法中移除观察者,以防止内存泄漏。
评论已关闭