Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove listener doesn't remove the listener #679

Closed
igloo12 opened this issue Sep 14, 2021 · 4 comments
Closed

Remove listener doesn't remove the listener #679

igloo12 opened this issue Sep 14, 2021 · 4 comments
Labels
question Further information is requested

Comments

@igloo12
Copy link

igloo12 commented Sep 14, 2021

I am listening to a provider with

void initState(){
super.initState();
 Provider.of<MyModel>(context, listen: false)
        .addListener(myModelListener);
}

and removing it with

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

when I trigger the provider after my view was disposed it throws a null exception

The following TypeErrorImpl was thrown while finalizing the widget tree:
Unexpected null value.

When the exception was thrown, this was the stack: 
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49      throw_
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 528:63  nullCheck
packages/flutter/src/widgets/framework.dart 3129:31                               get widget
packages/provider/src/provider.dart 343:16                                        _inheritedElementOf
packages/provider/src/provider.dart 295:30                                        of```
@igloo12 igloo12 added bug Something isn't working needs triage labels Sep 14, 2021
@rrousselGit rrousselGit added question Further information is requested and removed bug Something isn't working needs triage labels Sep 24, 2021
@rrousselGit
Copy link
Owner

You cannot call Provider.of within the dispose method.

@igloo12
Copy link
Author

igloo12 commented Sep 24, 2021

@rrousselGit How do I deregister the listener then when the view is destroyed?

@rrousselGit
Copy link
Owner

You should keep a reference on the provided value inside your state

MyModel? _myModel;

didChangeDependencies() {
  super.didChangeDependencies();
  _myModel = Provider.of<MyModel>();
}

dispose() {
  _myModel!.removeListener();
}

@rrousselGit
Copy link
Owner

👋
I'll close this since this was answered. Feel free to create a new issue if you still have the problem 😄

josephnglynn added a commit to josephnglynn/Flexify that referenced this issue Mar 9, 2024
=> rrousselGit/provider#679 shows how to do if
you still want listeners
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants