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

Add warning when using ref.notifyListeners() in build() #3897

Open
hamadmad opened this issue Dec 30, 2024 · 1 comment
Open

Add warning when using ref.notifyListeners() in build() #3897

hamadmad opened this issue Dec 30, 2024 · 1 comment
Assignees
Labels
enhancement New feature or request linter

Comments

@hamadmad
Copy link

Is your feature request related to a problem? Please describe.
I often (ab)use Riverpod as enhanced global variables like this:

FooContents _fooContents = FooContents();

@riverpod
class Foo extends _$Foo {
  @override
  FooContents build() {
    if(ref.watch(barProvider) == "baz") {
        _fooContents = ref.watch(barProvider).fooContents;
    }

    return __fooContents;
  }
}

This works fine so far. Now the naive way to return a list of all the foos could look like this:

List<FooContents> _fooContentsList =<FooContents>[];

@riverpod
class FooList extends _$FooList {
  @override
  List<FooContents> build() {
    bool fooContentsListChanged = false;
    if(ref.watch(barProvider) == "baz") {
        _fooContentsList.add(ref.watch(barProvider).fooContents);
        fooContentsListChanged = true;
    }

    if(fooContentsListChanged) {
        ref.notifyListeners();
    }
    return __fooContentsList;
  }
}

This does not work, because (as far as I understand it) notifyListeners is a NOP in build(). That's fine, because I'm quite heavily abusing the fact that Riverpod even allows mutability and I'm technically performing side effects in build. It's just very weird that notifyListeners seems to work but does nothing, which made debugging this very confusing. (I made the wrong assumption that my mistake had to be in the provider watching the broken one.)

Describe the solution you'd like
Of course I'd like Riverpod to allow even more abuse, but I believe it would be fine if there were a warning that there is no valid use of notifyListeners in build() (if I'm not missing any). I don't believe a documentation change would be sufficient because this is so weird to debug.

Thanks for Riverpod!

@rrousselGit
Copy link
Owner

Technically notifyListeners within build works ... if used asynchronously.

Like:

build() async {
  await something;
  ref.notifyListeners();
}

So a lint here would be a bit complex. And there's not that much value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request linter
Projects
None yet
Development

No branches or pull requests

2 participants