Hello guys, today I wanted to show you how I approached the topic of securing an application after it returns from the background using custom code and the action flow editor.
About function
This Dart code is related to handling the lifecycle states of a Flutter app, particularly focusing on what happens when the app goes to the background and when it is resumed. Here's a brief overview:
onAppBackground
Function: This function manages the lifecycle observer by first removing any existing observer and then adding a new one. It sets the context for the observer, which is used later when the app's state changes.AppLifecycleObserver
Class: This class is designed to monitor the app's lifecycle changes (such as when the app is paused or resumed). It uses theWidgetsBindingObserver
mixin, which allows it to listen to these lifecycle changes.Singleton Pattern: The class implements a singleton pattern, ensuring that only one instance of the observer exists throughout the app's lifecycle.
Lifecycle State Handling:
When the app is resumed (
AppLifecycleState.resumed
), the code checks how long the app was in the background. If it was in the background for more than 2 seconds, it navigates to a specific screen (named 'ProvidePin') using the stored context.When the app is paused (
AppLifecycleState.paused
), the code records the time, which is later used to calculate the duration the app spent in the background.
This setup is useful for implementing security features like requiring a PIN after the app has been in the background for a certain period.
How to do it?
Go to your project -> custom code -> Add custom action
Name action onAppBackground and paste my code https://gist.github.com/amicable-io/b8dccb0b03851546edb572bde34d1203
In line 40 edit "context!.goNamed('ProvidePin');" and in place of ProvidePin please provide your screen name where the user can provide a pin (YOU CAN DO THE SAME WITH BIOMETRIC JUST REDIRECT TO SCREEN WHERE YOU HAVE ACTION FOR IT)
Adjust duration in line 38. In my case, it is 2 seconds. It means if the app was in the background for more than 2 seconds ProvidePin screen will appear
Save your function
Go to the Build section of your app and create an Action block
In your screens where you want to have a PIN or BIOMETRIC authentication add an Action block On Page Load with Custom action "onAppBackgorund"
Test your app ๐
Additional features:
If you want to have also PIN authentication after the app was killed then create AppState "wasAppKilled" not persisted with and add it to the flow
And for curious people this is my "ProvidePin" action builder:
And for biometric authentication I added On Page Load