In my flutter application I have a button which starts an asynchronous network operation and displays a dialog while waiting for it to complete. Once completed, the dialog is popped from the navigation, but I am running into concurrency issues. Here's my code:
ElevatedButton(
onPressed: () async {
showDialog(
context: context,
builder: (context) => Center(child: CircularProgressIndicator()),
);
await asyncNetworkOperation();
Navigator.pop(context);
},
child: Text("Press here");
)
If the user taps on the Android back button while the network operation is in progress, the dialog gets popped ahead of time. And then, once the network operation completes, another Navigator.pop(context) is issued which pushes the navigation back one extra step.
What is the best way to avoid Navigator.pop from executing if the user already popped the dialog? I know I could prevent the back button from working altogether with the WillPopScope
widget, but I would like the user to have the ability to abort the operation should it take too long.
TLDR: How to prevent a Navigator.pop()
in an async frunction from popping a route which has already been popped?