I've been building an app that has a back arrow '<-' and cross 'X' in the app bar. Programmatically, I have included various commands, including Navigator.pop(context)
and to clear global data stored with a GetX data controller, like so:
onPressed: () {
try {
/// Clear data, so the app is ready to use again
c.updateValue('');
/// Close Screen
Navigator.pop(context);
} catch (e) {
print(
'Error when closing the database input window.');
}
},
In this instance, clearing the value means simply replacing whatever string is stored with an empty string.
Now, this works perfectly when either the back arrow or cross in the app bar are pressed. However, I've noticed on a physical device that when I make use of the phone's back arrow/button, which is outside of the app, whilst it moves the screen, it does not clear any of the data, as per the first statement in my onPressed
function above.
My question is, how do I get the same commands to take place when the user makes use of the phone's back button, compared to the app's programmed back button?
Thank you!
Wrap your Scaffold with WillPopScope and execute the same command on the onWillPop
like this:
return WillPopScope(
onWillPop: () async{
try {
/// Clear data, so the app is ready to use again
c.updateValue('');
return true; // true allows navigating back
} catch (e) {
print(
'Error when closing the database input window.');
return false; // false prevents navigating back
}
},
child: Scaffold(....),
);