Flutter 监听 app当前状态

runApp 创建的class添加事件

class CustomApp extends StatefulWidget {
  const CustomApp(this.route, {Key key}) : super(key: key);
  @override
  _CustomAppState createState() => _CustomAppState();
}

class _CustomAppState extends State with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();
    // 添加监听
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
  // 移除监听
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        debugPrint('应用程序可见并响应用户输入。');
        break;
      case AppLifecycleState.inactive:
        debugPrint('应用程序处于非活动状态,并且未接收用户输入');
        break;
      case AppLifecycleState.paused:
        debugPrint('用户当前看不到应用程序,没有响应');
        break;
      case AppLifecycleState.detached:
        debugPrint('该应用程序仍托管在颤振引擎上,但与任何主机视图分离');
        break;
      default:
    }
  }

你可能感兴趣的:(Flutter开发随记,flutter,生命周期,app杀死,app状态)