Unhandled Exception: A ChangeNotifier was used after being disposed

Issue

I’m getting this error message:

Unhandled Exception: A ModeManager was used after being disposed.

I’m using ChangeNotifier (class ModeManager) together with ChangeNotifierProvider.
Build method, where I create Provider looks like this:

@override
Widget build(BuildContext context) {
    return !_isLoaded ? Center(child: CircularProgressIndicator()) : ChangeNotifierProvider(
        create: (_) => ModeManager(_appUser),
        child: Scaffold(
            appBar: AppBar(
            title: Text('Connect Spotify'),
            ),
            body: AddSpotifyScreenBody(),
        ),
    );
}

Widget where I use provider looks something like this:

class _AddSpotifyScreenBodyState extends State<AddSpotifyScreenBody> {
  @override
  Widget build(BuildContext context) {
    var provider = Provider.of<ModeManager>(context);
    return Center(
      child: Padding(
        padding: EdgeInsets.all(20.0),
        child: Column(
          children: <Widget>[
            Text(provider.isCollecting ? 'COLLECTING NOW' : 'SHARING NOW'),
            //...some other widgets using provider...
          ],
        ),
      ),
    );
  }
}

Does anybody know what could cause this error or what am I doing wrong? Thank You very much.

Solution

It seems that you call notifyListeners() after disposing the widget with the ChangeNotifierProvider() .
This happened with me when a Future function call notifyListeners(). As mentioned here, you can override the notifyListeners method in the ChangeNotifier class :

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

@override
void notifyListeners() {
  if (!_disposed) {
    super.notifyListeners();
  }
}

don’t forget to declare the variable bool _disposed = false;

Answered By – Ismaeel Sherif

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *