How to handle app lifecycle with Flutter (on Andro

2019-08-13 15:20发布

问题:

Are there any Activity lifecycle methods in Flutter apps?

Like:

onCreate()
onResume()
onDestroy()

Or:

viewDidload()
viewWillAppear()

How to handle application lifecycle when making 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)