我想调用在退出应用程序时保存在SharedPreferences中的方法
我尝试了dispose()但不起作用
@override
void dispose() {
print("exit");
_subscription.cancel();
saveCounter();
super.dispose();
}
Future<void> saveCounter() async{
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('startNumber', _steps);
}
答案 0 :(得分:1)
Scaffold
包装WillPopScope
Future.value()
内的 true 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"),
),
),
);
}
}
您可以在此Github repo
中自行构建它