Widget的生命周期
-
StatelessWidget
StatelessElement createElement() Widget build(BuildContext context)
-
StatefulWidget
void initState() void didChangeDependencies() Widget build(BuildContext context) void reassemble() void didUpdateWidget(LifeCyclePage oldWidget) void deactivate() void dispose()
App的生命周期
App的生命周期需要通过WidgetsBindingObserver的didChangeAppLifecycleState来获取,在initState中添加监听WidgetsBinding.instance.addObserver(this);
resumed:可见并能响应用户的输入
inactiv:处在并不活动状态,无法处理用户响应
paused:不可见并不能响应用户的输入,但是在后台继续活动中
class LifeCyclePageAState extends State<LifeCyclePageA> with WidgetsBindingObserver {
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
print("app resumed");
break;
case AppLifecycleState.inactive:
print("app inactive");
break;
case AppLifecycleState.paused:
print("app paused");
break;
case AppLifecycleState.detached:
print("app detached");
break;
}
super.didChangeAppLifecycleState(state);
}
@override
void initState() {
print("initState A");
WidgetsBinding.instance.addObserver(this);
super.initState();
}
省略其他代码...
}
推到后台再回到前台打印如下