2

In my app I have a top-level ProviderScope widget which wraps my MaterialApp. Inside my HomePage, I'm using another Navigator widget, in which I use a switch case to manage routes. In this case, I'm following the marvel example from the riverpod git examples.

When my route is Routes.obra, everything works fine. I can access my provider at any time, but when I push another named route, such as Routes.colaboradores, my provider throws a Unimplemented error. I know that providers are scoped and that page Colaboradores() cannot access it. My question is: how could I organize my navigation in a way that obraProvider is avaliable on both pages?

ProviderScope(
      child: MaterialApp(
        navigatorKey: rootNavigatorKey, ...
final obraProvider = StateProvider<Obra>((ref) {
  throw UnimplementedError();
});

Navigator(
      key: loggedNavigatorKey,
      onGenerateRoute: (settings) {
        late Widget result;
        switch (settings.name) {
          case Routes.home:
            result = const Home();
            break;
          case Routes.obra:
            result = ProviderScope(
                overrides: [obraProvider.overrideWithValue(StateController(settings.arguments as Obra))],
                child: const Obra());
            break;
          case Routes.colaboradores:
            result = const Colaboradores();
            break;
        }
        return MaterialPageRoute(builder: (context) => result);
      },
    );

I can make it work if I get the provider before pushing a route and passing it as an argument like this, But I don't feel like this is the best approach for this scenario.

loggedNavigatorKey.currentState!.pushNamed(Routes.colaboradores, 
    arguments: ref.read(obraProvider));
case Routes.colaboradores:
            result = ProviderScope(
                overrides: [obraProvider.overrideWithValue(StateController(settings.arguments as Obra))],
                child: const Colaboradores());
            break;
Alan Cesar
  • 370
  • 3
  • 13

0 Answers0