Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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.

like image 429
Pritish Avatar asked Sep 17 '25 07:09

Pritish


1 Answers

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.

like image 87
Kirill Karmazin Avatar answered Sep 19 '25 15:09

Kirill Karmazin