flutter中获取应用生命周期主要用一个widgets绑定观察器---WidgetsBindingObserver。
核心代码如下:
import 'package:flutter/material.dart';
///如何获取flutter应用的生命周期
///WidgetsBindingObserver 是一个widgets绑定观察器,通过它我们可以监听应用的生命周期
class AppLifeCycle extends StatefulWidget {
@override
_AppLifeCycleState createState() => _AppLifeCycleState();
}
class _AppLifeCycleState extends State<AppLifeCycle> with WidgetsBindingObserver {
///添加监听器
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutter应用生命周期'),
),
body: Container(
child: Text('flutter应用生命周期'),
),
);
}
/// 生命周期发生变化时,会调用该方法
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
print('state = $state');
if(state == AppLifecycleState.paused) {
print('APP进入后台');
} else if (state == AppLifecycleState.resumed) {
print('APP进入前台');
} else if (state == AppLifecycleState.inactive) {
// print('应用处于非激活状态,并且未接收用户时调用,比如:来电话');
}
}
///移除监听器
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}
控制台打印信息如下:
flutter: state = AppLifecycleState.inactive
flutter: state = AppLifecycleState.paused
flutter: APP进入后台
flutter: state = AppLifecycleState.inactive
flutter: state = AppLifecycleState.resumed
flutter: APP进入前台