Riverpod question about using ref.listenManual

380 Views Asked by At

Please check the following code below.

  void initState() {
   ref.listenManual(
      timerControllerProvider,
      (previous, next) {       
        if (next.remainingSeconds == 300) {
          showAlertDialogButton_1(context, "5 Minutes remaining");
        } else if (next.remainingSeconds == 0) {
                   context.goNamed(NameConstants.timeFinishPage,
             );
          
        }
      },
    ); 
}

My question is.. Can i use navigation from initState ?

2

There are 2 best solutions below

1
On

You'll want to use fireImmediately: true if you want to possibly show the modal immediately:

@override
void initState() {
  super.initState();
  ref.listenManual(
    provider,
    fireImmediately: true,
    (prev, next) {
      if (<something>) showModal();
    },
  );
}

Adding to this, you're not naturally allowed to show modals directly inside initState. You'll have to delay the showModal:

SchedulerBinding.instance.addPostFrameCallback(() => showModal(...));
1
On

Also works for navigation:

@override
void initState() {
  super.initState();
  ref.listenManual(
    myProvider,
    fireImmediately: true,
    (prev, next) {
      final config = next.value!;
      if (config.step == OrderStep.login) {
        SchedulerBinding.instance.addPostFrameCallback((_) => context.pushReplacement(pathLogin));
      }
    },
  );
}