Sitemap

[FlutterTips] Using mixin to have access to Application Lifecycle State

2 min readJun 13, 2021

Two weeks ago, I had to implement an automatic refresh when the application wakes up. In Android this is pretty simple, you have to override the onResumed method. In Flutter it’s different, you can do it with a mixin.

A mixin is a functionality that you can reuse in in a multiple class hierarchies. If you don’t know what a mixin is, you can read more about it here :

The WidgetsBindingObserver class is a mixin that allows you to register your classes to the Widgets layer binding, you can do this with addObserver and removeObserver methods.

An app in flutter can have 4 states according to the documentation :

  • detached : The application is still hosted on a flutter engine but is detached from any host views.
  • inactive : The application is in an inactive state and is not receiving user input.
  • paused: The application is not currently visible to the user, not responding to user input, and running in the background.
  • resumed: The application is visible and responding to user input.

You can read more about it here : https://api.flutter.dev/flutter/dart-ui/AppLifecycleState-class.html

Now, let’s implement this mixin!

To capture the change of lifecycle state, you need to override 3 methods in your widget : initState, dispose and didChangeAppLifecycleState.

In the two first, register/unregister your Widget. The last one is where you implement your behaviour, according to the state.

You can find an example code below:

In this snippet, everytime the app is resumed. I’m fetching a new picture. Here is the result:

If you want the full code of this example, you can find it on my github here : https://github.com/nsalleron/flutter_lifecycle_state

Hope this helps!

--

--

Nicolas Salleron
Nicolas Salleron

Written by Nicolas Salleron

co-funder of www.monparcsolaire.fr, online platform providing information and regular articles on photovoltaics.

Responses (1)