问题
My flutter app is showing a splash screen (statefulWidget
) as a first route. This route is showing an animation while, on the background, calling an API to get some data.
Once the data has been received and the animation is complete, it navigates to the second route.
All works fine, except that, when calling the Navigator
to navigate to the second route, the second route is shown, but i can see again the response from the API on the first route, that is being called.
It turns out that, when the second route is built, the build method of the previous route is called too, making an unnecessary API call again.
How to avoid this behaviour?, I believe this must be a bug on Flutter
??
current flow (non-desired): SplashRoute(build) ---> Navigator ---> HomeRoute(build)+SplashRoute(build)
desired flow: SplashRoute(build) ---> Navigator ---> HomeRoute(build)
回答1:
What you are trying to do is to work against the framework. It's a futile effort. Instead, you should work with the framework. Here is why and how:
Build methods should not make API requests. Build methods should use fields of your state class to generate a UI without any side effects.
Please move your API calls to the initState
method, save their results in fields of your state class with setState
and get the build
method to use them without generating any side effects.
来源:https://stackoverflow.com/questions/58832813/flutter-avoid-build-method-of-previous-route-being-called-when-navigate-to-ne