简体   繁体   English

在静态方法中传递 BuildContext 会导致 Flutter 中的内存泄漏吗?

[英]Does passing BuildContext inside a static method causes memory leak in Flutter?

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.该对话框需要BuildContext所以我创建了一个类并添加了一个静态方法来显示对话框,并在静态方法中传递了一个BuildContext作为参数。 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.就原生 Android 而言,我知道如果静态方法返回 UI,则在静态方法中传递活动上下文会导致方法泄漏。

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.根据此 dart-lang 问题中的答案,只要存在可访问的引用 - 对象将保存在内存中。

So, in general, it is not recommended to store a BuildContext object in a static field.所以,一般情况下,不建议在静态字段中存储BuildContext对象。

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.但是,如果您获得了不会在应用程序的生命周期内重新创建的顶级小部件的BuildContext - 应该没问题。 If it might be disposed - overwrite the dispose() method and clear the reference by assigning a null value.如果它可能被处理 - 覆盖dispose()方法并通过分配null值清除引用。

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传递给它们,因为只要任务将执行,它肯定会导致内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM