How to dispose subscription?

How can I dispose subscription if my class is not in StatefulWidge? Is there any method?

class EventNotifier extends ValueNotifier<List<String>> {
  EventNotifier(List<String> value) : super(value);
  final List<String> events = ['add', 'delete', 'edit'];
  final stream = Stream.periodic(const Duration(seconds: 5));
  late final streamSub = stream.listen(
    (event) {

>Solution :

I don’t believe it’s necessary in this case, since both the stream and subscription will be freed by the GC when the instance is freed.

However, ValueNotifier does have a dispose method. You can override it, and cancel your stream from there if you need to:

class EventNotifier extends ValueNotifier<List<String>> {
  // Omitted

  void dispose() {

Leave a Reply