Search code examples
flutterriverpodflutter-go-router

How to dispose a screen BEFORE the new screen is initialized, during go_router navigation?


I have a Screen A that is calling context.pushReplacement(ScreenA.route), which means it is calling pushReplacement on itself. The problem is, the new copy of Screen A is initialized BEFORE the old Screen A is disposed.

This is a problem since I am using Riverpod, and I need the Provider (with autoDispose) of Screen A to be disposed, and THEN recreated on the new copy of Screen A. What is happening is since the new Screen A is being created before the old one is disposed, the provider is never not being listened to, and therefore never being disposed. So the new Screen A is being created with the same instance of the provider, which creates problems in my application.

Is there any way to have the new screen that is being created with context.pushReplacement to wait until the old screen is disposed so it can be created?

Thanks.


Solution

  • Perhaps you could manually reset the required provider via ref.invalidate(provider) or via ref.refresh(provider) if you need the value of that provider (or to do a rebuild immediately).

    context.pushReplacement(ScreenA.route);
    ref.invalidate(provider);