Home > Blockchain >  Flutter // Understanding dispose
Flutter // Understanding dispose

Time:02-17

The more things I do, the more often I run across things that need disposing (e. g. Timers and ScrollControllers). Two questions:

  1. Is there a way to see/know what things need to be disposed? Or is it just a thing you need to learn by heart? For example: At the moment I'm not sure, if I need to dispose of providers.
  2. Do I need to expose things (e. g. Timers) in stateless widgets? If so how? Or do I turn a widget stateful just so I gain access to the dispose method? That seems wasteful.

Thanks!

CodePudding user response:

  1. If disposing is needed, it's usually stated in docs.
  2. It's not about turning into a stateful widget "just to gain access to the dispose method". It's turning into a stateful widget because it has a state. If it contains a timer, it already implies having a state. Think of stateless widgets as pure functions – you can call them several times and there should be no side effects. Timer is such a side effect since you don't want it to be re-created on every stateless widget creating. Also, there's no significant performance impact on converting stateless widget to stateful.
  • Related