Provider: Looking up a deactivated widget's ancestor is unsafe.

Created on 3 Feb 2020  Â·  3Comments  Â·  Source: rrousselGit/provider

When I tried to call a method inside of State dispose method like below

  @override
  void dispose() {
    Provider.of<AppProvider>(context, listen: false).close();
    super.dispose();
  }

I got this error, even with minimum test app. I'm currently using provider: ^4.0.2. How can I solve this.

The following assertion was thrown while finalizing the widget tree:
Looking up a deactivated widget's ancestor is unsafe.

At this point the state of the widget's element tree is no longer stable.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

When the exception was thrown, this was the stack
#0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> 
package:flutter/…/widgets/framework.dart:3508
#1      Element._debugCheckStateIsActiveForAncestorLookup 
package:flutter/…/widgets/framework.dart:3522
#2      Element.getElementForInheritedWidgetOfExactType 
package:flutter/…/widgets/framework.dart:3588
#3      Provider.of 
package:provider/src/provider.dart:219
#4      _MySecondPageState.dispose 
package:test_space/main.dart:138
...

Most helpful comment

I solved this. Thanks

  AppProvider _appProvider;
  @override
  void didChangeDependencies() {
    _appProvider = Provider.of<AppProvider>(context, listen: false);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _appProvider.close();
    super.dispose();
  }

All 3 comments

You can try to follow the instructions of your error:

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

@smiLLe Thanks for help. I actually don't understand how to implement it. Could you give me an example.

I used to do it the same without this exception before. Is this because new flutter version?
Also, I realized there is the deactivate() method, can I use deactivate() method instead of dispose() method?

I solved this. Thanks

  AppProvider _appProvider;
  @override
  void didChangeDependencies() {
    _appProvider = Provider.of<AppProvider>(context, listen: false);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _appProvider.close();
    super.dispose();
  }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Alfie-AD picture Alfie-AD  Â·  4Comments

prasadsunny1 picture prasadsunny1  Â·  6Comments

MaxTenco picture MaxTenco  Â·  5Comments

hou3172568 picture hou3172568  Â·  4Comments

rrousselGit picture rrousselGit  Â·  3Comments