Flutter: avoid build() method of previous route being called when navigate to next route

偶尔善良 提交于 2020-03-26 03:02:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!