What is the correct way of providing a GoRouter instance with riverpod?

2k Views Asked by At

I'm trying to provide an instance of GoRouter with riverpod. However, this results in the "The riverpod_generator package does not support ChangeNotifier values" warning to be displayed:

enter image description here

My question is, what would be the correct way of achieving this?

2

There are 2 best solutions below

1
On BEST ANSWER

The warning is here to warn you about how Riverpod will neither listen to the ChangeNotifier nor dispose of it when the state is destroyed (which is what would happen if you were to use ChangeNotifierProvider).

If you do not care about these points, you can safely ignore the lint.
I'd recommend disposing the notifier manually as followed:

@riverpod
// ignore: unsupported_provider_value
GoRouter example(ExampleRef ref) {
  final router = GoRouter(...);
  ref.onDispose(router.dispose);
  return router;
}
0
On

See this excellent article by Andrea: https://codewithandrea.com/articles/flutter-navigate-without-context-gorouter-riverpod/

Basically, what you want is a non-generator with the GoRouter object itself:

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