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.
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.
So, in general, it is not recommended to store a BuildContext
object in a static field.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With