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?
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.