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.
Asked
Active
Viewed 5,258 times
4

BraveEvidence
- 53
- 11
- 45
- 119
1 Answers
5
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.

Kirill Karmazin
- 6,256
- 2
- 54
- 42
-
1so what is the solution what o pass at the place of context to show a dialog in model class – s.j Oct 07 '20 at 09:25