Flutter App lifecycle (Android/ Ios )

2019-03-29 09:16发布

问题:

Is any Activity life cycle method in flutter app android ?

Like:

onCreate()
onResume()
onDestroy()

Or:

viewDidload()
viewWillAppear()

How to handle application life cycle when make an app with flutter?

回答1:

There is a method called when the system put the app in the background or return the app to foreground named didChangeAppLifecycleState.

Example with widgets:

  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');
  }
}

Also there are CONSTANTS to know the states that an application can be in, eg:

  1. inactive
  2. paused
  3. resumed
  4. suspending

The usage of these constants would be the value of the constant e.g:

const AppLifecycleState(state)