Reputation: 9830
I'm trying to access a provider method in the dispose function.
@override
void dispose() {
if (canRemoveData) Provider.of<MyProvider>(context, listen: false).clearData();
super.dispose();
}
but when that gets called I get the error:
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.
What am I doing wrong and how can I fix it?
Upvotes: 2
Views: 3821
Reputation: 477
you can override deactivate method in StatefullWidget
@override
void deactivate() {
super.deactivate();
context.read<PinScreenProvider>().destroy();
}
Note: destroy is a function, where i written clear data
Upvotes: 1
Reputation: 251
The error description basically says it all. The dispose()
method is intended for disposing your widget's state dependencies and controllers, so you shouldn't try to find ancestors of this widget at this point because your widget is already deleted from the widget tree.
You should instead make a variable in your state and provide MyProvider
value in initState()
. Then you would be able to call MyProvider#clearData() from dispose as such:
class _MyWidgetState extends State<MyWidget> {
MyProvider _myProvider;
@override
void initState() {
super.initState();
_myProvider = Provider.of<MyProvider>(context, listen: false);
}
@override
void dispose() {
if (canRemoveData) _myProvider.clearData();
super.dispose();
}
@override
Widget build(BuildContext context) {
// implement
}
}
Also if you provide MyProvider as a direct parent of your widget and after it's dispose you wouldn't need MyProvider anywhere else, you could use ProxyProvider dispose method like that:
ProxyProvider<SomeDependency, MyProvider>(
update: (context, someDependency, previous) => previous ?? MyProvider(someDependency),
dispose: (context, myProvider) => myProvider.clearData(),
),
Upvotes: 7