2

i want to call a method to save in SharedPreferences when app exit

i tried dispose() but doesn't work

 @override
void dispose() {
  print("exit");
  _subscription.cancel(); 
  saveCounter(); 
  super.dispose();
}

Future<void> saveCounter() async{
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('startNumber', _steps);
}
2
  • where do you put dispose method? Is it on statefulwidget? Commented Aug 30, 2019 at 23:05
  • @ejabu yes its statefulwidget class return scaffold Commented Aug 30, 2019 at 23:44

1 Answer 1

1
  • we can wrap Scaffold using WillPopScope
  • we can execute saveCounter inside the function
  • ensure it will return true that wrapped inside Future.value()
class WillPopScreen extends StatelessWidget {
  Future<void> saveCounter() async {
    final prefs = await SharedPreferences.getInstance(); // we can save state
    await prefs.setInt('startNumber', _steps);
  }

  Future<bool> onCloseEvent() async {
    await saveCounter();
    return Future.value(true); // we cannot put "return true"
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: onCloseEvent, // will interrupt our scaffold dismissal
      child: Scaffold(
        appBar: AppBar(
          title: Text('Will Pop Interrupt'),
        ),
        body: Center(
          child: Text("Execute method when Closing"),
        ),
      ),
    );
  }
}

Fully working repo

You can build it yourself in this Github repo

Demo

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

not working i want it to run when someone close the app
@suhaibsalem any luck with this ? I am also looking for the same. How to free resources when app is removed/closed form recently opened app tray

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.