Flutter:在导航到下一条路线时,避免调用上一条路线的build()方法 [英] Flutter: avoid build() method of previous route being called when navigate to next route

查看:95
本文介绍了Flutter:在导航到下一条路线时,避免调用上一条路线的build()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的flutter应用程序显示了启动屏幕( statefulWidget )作为第一条路线。此路线显示的是动画,而在后台调用API来获取一些数据。

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.

一切正常,除了调用 Navigator 导航到第二条路线时,显示了第二条路线,但是我可以再次看到来自第一条路线的API的响应。

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.

事实证明,当第二条路线生成后,也会调用上一条路径的build方法,再次进行不必要的API调用。

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.

如何避免这种行为?,我相信这一定是一个错误在 Flutter ??

How to avoid this behaviour?, I believe this must be a bug on Flutter??

当前流量(不需要)上:SplashRoute(build)--- >导航器---> HomeRoute(构建)+ SplashRoute(构建)

所需的流:SplashRoute(build)--->导航器- -> HomeRoute(build)

推荐答案

您正在尝试做的是针对框架。这是徒劳的。相反,您应该使用框架。以下是原因和方法:

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:

构建方法不应发出API请求。生成方法应使用状态类的字段来生成没有任何副作用的UI。

Build methods should not make API requests. Build methods should use fields of your state class to generate a UI without any side effects.

请将您的API调用移至 initState 方法,并使用<$将其结果保存在州类的字段中c $ c> setState 并获取 build 方法以使用它们而不会产生任何副作用。

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.

这篇关于Flutter:在导航到下一条路线时,避免调用上一条路线的build()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆