在静态方法中传递BuildContext是否会导致Flutter中的内存泄漏? [英] Does passing BuildContext inside a static method causes memory leak in Flutter?

查看:230
本文介绍了在静态方法中传递BuildContext是否会导致Flutter中的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示一个对话框,该对话框可在我的应用程序中的任何地方重用。该对话框需要 BuildContext ,因此我创建了一个类并添加了一个静态方法来显示该对话框,并在该对话框中传递了 BuildContext 静态方法作为参数。这会导致内存泄漏吗?就本机Android而言,我知道如果静态方法返回UI,则在静态方法内部传递活动上下文会导致方法泄漏。

I am trying to display a dialog which will be reusable everywhere in my app. The dialog requires BuildContext so I created a class and added a static method to show the dialog and passed a BuildContext in the static method as parameters. Does this cause any memory leak?? As far as Native Android goes I know that passing activity context inside a static method causes method leak if the static method is returning an UI.

推荐答案

可能是。这将防止垃圾收集器从该对象释放内存。根据此dart-lang问题中的答案,只要存在引用-该对象将保留在内存中。

Potentially yes. This will prevent the garbage collector from freeing memory from this object. As per answer in this dart-lang issue as long as there is a reachable reference - the object will be kept in memory.

因此,通常不建议存储 BuildContext 静态字段中的对象。

So, in general, it is not recommended to store a BuildContext object in a static field.

但是,如果您获得顶部窗口小部件的 BuildContext ,则该窗口小部件不会在该应用程序-应该没问题。
如果可以处置-覆盖 dispose()方法,并通过分配 null 清除引用值。

But if you get a BuildContext of the top widget which is not going to be recreated within the lifetime spawn of the app - it should be ok. If it might be disposed - overwrite the dispose() method and clear the reference by assigning a null value.

根据长期存在的异步任务-我不建议将其传递给 BuildContext ,因为只要执行任务,肯定会导致内存泄漏。

As per the long-living async tasks - I don't recommend passing them a BuildContext because it will definitely cause a memory leak for as long the task will be executing.

这篇关于在静态方法中传递BuildContext是否会导致Flutter中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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