0

I have more than one question about controllers :

Do I need to dispose of every controller I create, even if it's TextEditingController or AnimationController?

StatelessWidget and StatefulWidget, Do I need to convert StatelessWidget to stateful to dispose of the controller or Stateless can dispose automatically and no need to convert?

Do I need to controller.removeListener({}()) even if I controller.dispose() ?

  • 1
    Does this answer your question? [Removing listerers before dispose flutter](https://stackoverflow.com/questions/61759948/removing-listerers-before-dispose-flutter) – osaxma Jan 13 '22 at 11:57
  • You need to dispose all the controllers you create. You only need to remove the listeners if you didn't create the controller or if the listener was added in another widget (i.e. not the same widget where the controller was created). – osaxma Jan 13 '22 at 11:58
  • how to dispose controller if the widget is StatelessWidget? and why dispose isn't enough, instead of removeListener? – Sherif Raafat Jan 13 '22 at 12:10
  • You need to convert the widget to Stateful Widget if you're initializing a controller there. Dispose is enough if you create the controller. But sometimes, the controller comes to the widget as an argument, and in this case, you don't need to dispose it (wherever it was created, it should be disposed). If the controller comes as an argument and you add a listener, then you need to remove the listener but you don't dispose the controller since it was not created there. So if u pass a controller to a StatelessWidget as an argument, then the StatelessWidget doesn't need to dispose it. – osaxma Jan 13 '22 at 12:23
  • Look at how `TextField` handles it. If you pass a controller to `TextField`, it doesn't dispose it, but if you don't pass a controller, `TextField` creates one and it disposes it on its own: See source here https://github.com/flutter/flutter/blob/fd9ce277482c906a2324066c4107779536d6edfe/packages/flutter/lib/src/material/text_field.dart#L973 – osaxma Jan 13 '22 at 12:27
  • Is converting StatelessWidget to Stateful is more expensive than dispose controller? – Sherif Raafat Jan 13 '22 at 12:33

0 Answers0