The title pretty much explains what I want to do. I have an app where the init state has async methods to be called. There are also buttons in the build which when pressed execute async methods (api calls).
The problem is that if I navigate to a new screen before the previous screen has completed fully loading, the app shows ambigious behaviour like not loading the next screens completely or crashing altogether.
My question is that what happens to async methods of the previous screen when you navigate to a new screen before they finished executing?
Is there a way to pause/cancel the execution of those async methods when you navigate to a new screen and resume/reload when you come back to that screen?
OR
Is there a way to only navigate to the new screen when the previous screen has completed fully loading.
I apologize if there seem knowledge gaps in my question. TIA
CodePudding user response:
If you navigate from screen 1 to screen 2 using Navigator.push(...);
then screen 1 state loading should finish loading your API state/data even with screen 2 being displayed. But if you use Navigator.pushReplacement(...);
to navigate from screen 1 to screen 2, then the loading of your screen 1 state should be stopped, as in the hierarchy your screen has been replaced by screen 2.
If you want to call a function only when your screen state 1 has fully loaded you can use:
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => myFunction());
}
CodePudding user response:
If you navigate to next screen without waiting, it still running until finish. All normal mobile apps have something called loading widget. It appears when you start to call async method & disappears when it finish. For me, I often use Stack
for any screen, so it would prevent users from pressing anything on their phone. If you want to wait util move to next screen, use await
.