Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProviderContainer and GoRouter

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?

like image 962
bqubique Avatar asked Jun 23 '26 22:06

bqubique


1 Answers

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.

like image 154
Ruble Avatar answered Jun 25 '26 23:06

Ruble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!