iDecode
iDecode

Reputation: 28886

How to change provider state within itself?

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.

Upvotes: 1

Views: 485

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276967

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

Upvotes: 2

Related Questions