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

How to use context.watch in initState #876

Closed
magic3584 opened this issue Apr 19, 2024 · 2 comments
Closed

How to use context.watch in initState #876

magic3584 opened this issue Apr 19, 2024 · 2 comments
Assignees
Labels
bug Something isn't working needs triage

Comments

@magic3584
Copy link

Describe the bug
Cannot use context.watch() in initState

To Reproduce

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      final needRefresh = context.watch<MyState>().needRefresh;
      _refresh(needRefresh);
    });
  }

  _refresh(needRefresh) {
    _fetchData(type: type);
  }

Expected behavior
I have several pages which showing different type data

// pageA.dart & pageB.dart
  @override
  void initState() {
    super.initState();
    _fetchData(type: type)
  }

So I wanna listening to MyState.needRefresh change and re-fetch the data whatever which page is showing.
It works fine in build() except at least called once, so I move them in to initState(), here comes the error

flutter: 'package:provider/src/provider.dart': Failed assertion: line 274 pos 7: 'context.owner!.debugBuilding ||
          listen == false ||
          debugIsInInheritedProviderUpdate': Tried to listen to a value exposed with provider, from outside of the widget tree.

This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.

To fix, write:
Provider.of<MyState>(context, listen: false);

It is unsupported because may pointlessly rebuild the widget associated to the
event handler, when the widget tree doesn't care about the value.

Please tell me how can I fix this.

@magic3584 magic3584 added bug Something isn't working needs triage labels Apr 19, 2024
@rrousselGit
Copy link
Owner

You don't. Use context.read inside initState

@magic3584
Copy link
Author

You don't. Use context.read inside initState

But I wanna call some function when value changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs triage
Projects
None yet
Development

No branches or pull requests

2 participants