Home > database >  How to change provider state within itself?
How to change provider state within itself?

Time:11-19

Minimal reproducible code:

final provider = StateProvider<bool>((ref) {
  Timer? _timer;

  ref.listenSelf((_, flag) {
    if (!flag) {
      _timer = Timer(Duration(seconds: 5), () {
        ref.read(this).state = true;
      });
    }
  });

  // ... disposing timer, etc.

  return true;
});

The above provider returns true initially, and I change that value to false in a widget and 5s after that, I want to change this value back to true. I'm using listenSelf but I'm not able to do it.


Note:

I don't want to use StateNotifier with StateNotifierProvider.

CodePudding user response:

The ref of a provider generally exposes a way to modify itself.
In the case of StateProvider, you can do Ref.controller to obtain the StateController

You can therefore do ref.controller.state = true

  • Related