Is there a way to call specific code right before the app is killed or moves to the background?

9k Views Asked by At

I want to write the user's preferences to a file before they leave the app, so I'm looking for something in Flutter like Android's onPause() or onStop() methods. Is this something so platform-specific that I'd need to write services for it and actually use Android/iOS's specific methods for these situations or is there a way to do it only using Flutter/Dart?

2

There are 2 best solutions below

5
On BEST ANSWER

My understaning is that this is possible with the didChangeAppLifecycleState callback on the WidgetsBindingObserver: https://docs.flutter.io/flutter/widgets/WidgetsBindingObserver-class.html

Examples: https://github.com/flutter/flutter/search?utf8=%E2%9C%93&q=didChangeAppLifecycleState

We definitely need some better docs and examples here. I've filed: https://github.com/flutter/flutter/issues/7394

If these are not sufficient for your needs, it is also possible to listen for any events in your Objective-C or Java code and forward those along to Dart via HostMessages (documented at https://flutter.io/platform-services).

0
On

This is example code how you do it

first you need to add with WidgetsBindingObserver then dont forget to init & dispose the WidgetsBindng then you can call it from didChangeAppLifecycleState