9

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?

Reagankm
  • 4,780
  • 9
  • 27
  • 52
  • See also: https://stackoverflow.com/questions/60184497/how-to-execute-code-before-app-exit-flutter/65101428#65101428 – Suragch Dec 02 '20 at 02:44

2 Answers2

5

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).

Reagankm
  • 4,780
  • 9
  • 27
  • 52
Eric Seidel
  • 3,282
  • 1
  • 15
  • 22
  • The problem is that currently there is no event sent when the Activity on Android is stopped (which means the Dart VM isolate is destroyed). The [AppLifecycleState](https://docs.flutter.io/flutter/dart-ui/AppLifecycleState-class.html) has only a _paused_ event, no _destroyed_. See http://stackoverflow.com/questions/41924890/how-do-i-run-code-in-the-background-even-with-the-screen-off/42041981 – raju-bitter Feb 09 '17 at 08:12
  • 10
    On app kill i have to call api. Tried calling apis in dispose() method and also tried to call apis on AppLifecycleState.detached. both doesn't work. – mayur.pancholi Feb 02 '21 at 10:20
  • 1
    First link is dead. – Pratik Butani Dec 14 '21 at 06:22
  • 1
    @mayur.p did you find any solution? – saigopi.me Feb 14 '22 at 05:15
  • did you find any solution? – Ahmet Aydemir May 11 '22 at 12:45
0

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

rvng
  • 156
  • 1
  • 7