Get a provider method in the dispose method not working
Asked Answered
I

2

2

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?

Instructions answered 24/11, 2020 at 6:42 Comment(0)
P
7

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(),
  ),
Pullman answered 24/11, 2020 at 8:59 Comment(0)
R
0

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

Religionism answered 14/8, 2022 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.