Flutter App生命周期(Android/Ios)

Dee*_*yan 10 android ios dart flutter

Activity应用程序android中的任何Activity生命周期方法?

喜欢:

onCreate()
onResume()
onDestroy()
Run Code Online (Sandbox Code Playgroud)

要么:

viewDidload()
viewWillAppear()
Run Code Online (Sandbox Code Playgroud)

如何使用颤动的应用程序处理应用程序生命周期?

小智 15

当系统将应用程序放在后台或将应用程序返回到前台命名时,会调用一种方法didChangeAppLifecycleState.

小部件示例:

  class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  AppLifecycleState _notification;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() { _notification = state; });
  }

  @override
  Widget build(BuildContext context) {
    return new Text('Last notification: $_notification');
  }
}
Run Code Online (Sandbox Code Playgroud)

还有CONSTANTS可以知道应用程序可以处于的状态,例如:

  1. 待用
  2. 暂停
  3. 恢复
  4. 暂停

这些常量的用法将是常量的值,例如:

const AppLifecycleState(state)


Cop*_*oad 9

运行以下代码,按主页按钮,然后重新打开应用程序以查看其工作情况。有 4 个AppLifecycleState

resumed:应用程序可见并响应用户输入。

inactive:应用程序处于非活动状态并且不接收用户输入。

已暂停:应用程序当前对用户不可见,不响应用户输入,并在后台运行。

分离:应用程序仍然托管在 flutter 引擎上,但与任何主机视图分离。

空安全代码:

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> 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) {
    super.didChangeAppLifecycleState(state);
    print('Current state = $state');
  }

  @override
  Widget build(BuildContext context) => Scaffold();
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*ena 7

Flutter 版本 3.13 添加了 AppLifecycleListener,因此现在您可以监听 show、pause、resume、restart 等。

 _listener = AppLifecycleListener(
 onShow: () => _handleTransition('show'),
 onResume: () => _handleTransition('resume'),
 onHide: () => _handleTransition('hide'),
 onInactive: () => _handleTransition('inactive'),
 onPause: () => _handleTransition('pause'),
 onDetach: () => _handleTransition('detach'),
 onRestart: () => _handleTransition('restart'),
 // This fires for each state change. Callbacks above fire only for
 // specific state transitions.
 onStateChange: _handleStateChange,
);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看flutter repo 中的示例