skip to Main Content

I want to read the GoRouter outside of main() and outside of any widget.

GoRouter provider is defined as follows:

final goRouterProvider = Provider<GoRouter>(
  (ref) {
    return GoRouter(...);
}

Then when I’m initializing flutter_local_notifications I want to read this provider using ProviderContainer, similar to how I’m doing on main() method:

static final FlutterLocalNotificationsPlugin _localNotificationsPlugin =FlutterLocalNotificationsPlugin();

_localNotificationsPlugin.initialize(
  initializationSettings,
  onDidReceiveNotificationResponse: (details) async {
      final container = ProviderContainer();
      container.read(goRouterProvider).pushNamed(AppRoute.someRandomRoute.name);
  },
);

In this case I still end up in the same screen (no navigation action is taken) but with the same logs as when GoRouter initialises (due to debugLogDiagnostics: true flag).

I compared this to passing down the container from the main() method which does navigate to the destination as expected.

Does this mean that ProviderContainer().read(goRouterProvider) is creating a new GoRouter instance?

2

Answers


  1. Yes, that’s right, it’s a new copy. To get the old instance, you need the very container in which it will lie.

    You can either cast a container with an argument or get it through a BuildContext:

    final providerContainer = ProviderScope.containerOf(context);
    

    But one way or another, you need access to the container to get the value of the old instances.

    Login or Signup to reply.
  2. The description of ProviderContainer indicates that it is "an object that stores the state of the providers and allows overriding the behavior of a specific provider". Which means that the states of your providers are scoped to that container.

    When you are using Riverpod in a Flutter app, the container is implicitly created for you by ProviderScope, which means that if you create another container somewhere else it will not be the same as the one used internally by you Flutter app… and consequently they will NOT share the same states.

    You could just declare your router as a global variable, for example in a <router.dart> file have:

    /// Navigation router.
    final GoRouter kRouter = new GoRouter(
     ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search