In Flutter and Dart, if I mix-in a ChangeNotifier, or use ValueNotifier<T> for example (_counter = ValueNotifier<int>(0)) should I always dispose() it? I understand that it has a dispose() member, which clears the listeners list. But in most examples I've found on the web dispose() is not utilized. I think that in most (all?) practical cases, e.g., when ListenableBuilders are used, the listeners will clean up for themselves, i.e., remove their listeners during their dispose() (this should be the case with ListenableBuilder, unless I'm mistaken?), so to implement/call dispose() for notifiers is not needed?
I'm having a hard time drafting the scenario where ommitting dispose() (on the notifier part, i.e., in the class that extends/mixes-in ChangeNotifier or defines/exposes ValueNotifier<T> objects) would create a memory leak or any other problem. Could you please help me clarify whether my thinking is correct, in other words - can I safely ignore dispose()ing notifiers?
To clarify - I know that if something is disposable, it would make sense to dispose() it eventually by default. But in this particular case, I think "dangling listeners" should not be a problem, if the mechanism is not misused by the client. I.e., all clients should unsubscribe when they don't need the notifications anymore, and if the notifier goes out of the scope (= is disposed) before this happens, this indicates the problem with the client logic anyway, is it not? In other words, if not disposing the notifier creates a memory leak, that's because of the faulty clients first and foremost, is it not?
If disposing adds too much complexity, like extra classes or a stateful widget, you can skip it. Most states are lazy or global anyway. However, if you're already using provider with scopes or a stateful widget, disposing is better. It ensures the notifier isn't listened to and Flutter clears it from memory.
ValueNotifiers have a specific memory allocation removed upon disposal. Flutter also has garbage collectors! So if the class that hold your value notifier is destroyed, Flutter will eventually dispose it for you. Listeners are also just lightweight callbacks, unlike stream subscriptions.
So yeah, you can safely ignore them for the predictable cases you mentioned. But counting on it isn't scalable/testable for big projects.