Provider: How to check if ChangeNotifier has been disposed

Created on 21 May 2019  路  5Comments  路  Source: rrousselGit/provider

I'm just trying out Provider for the first time, and struggling to find the equivalent of State's mounted property.

I have a class that mixes in ChangeNotifier. In one of its methods it awaits on a network call, then notifyListeners() with the result of that network call.

If the user has navigated away while the network call is pending, I get an error

E/flutter (27530): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: A XXX was used after being disposed.
E/flutter (27530): Once you have called dispose() on a XXX, it can no longer be used.
E/flutter (27530): #0      XXX&Object&ChangeNotifier._debugAssertNotDisposed.<anonymous closure> (package:flutter/src/foundation/change_notifier.dart:105:9)
E/flutter (27530): #1      XXX&Object&ChangeNotifier._debugAssertNotDisposed (package:flutter/src/foundation/change_notifier.dart:111:6)
E/flutter (27530): #2      XXX&Object&ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:200:12)

In the basic StatefulWidget scenario, I would just check if (mounted) before calling setState. Is there an equivalent for ChangeNotifier?

Thanks!

Most helpful comment

true and false should be the opposite for the _mounted property in the above code...

All 5 comments

You can override dispose to implement a mounted yourself

@rrousselGit @wemped Can you show me how you did it?

@rrousselGit How to do it ?

abstract class Example {
  bool _mounted = false;
  bool get mounted => _mounted;

  @override
  void dispose() {
    super.dispose();
    _mounted = true; 
  }
}

true and false should be the opposite for the _mounted property in the above code...

Was this page helpful?
0 / 5 - 0 ratings