'Providing bloc to a new page using named route

I am trying to provide a local bloc to a new page, I found some way to do this by using an anonymous route but it doesn't look elegant

   Navigator.push(
     context,
     MaterialPageRoute(builder: (context) {
        return BlocProvider.value(
            value: context.bloc<MyBloc>(),
            child: NewPage());
     }),
   );

What I want is to do the same thing but using a named route and without creating a global bloc as I simply can't



Solution 1:[1]

  1. Create app_router.dart file. app_router.dart
class AppRouter {
  final LocalBloc _localBloc = LocalBloc();

  Route onGenerateRoute(RouteSettings routeSettings) {
    switch (routeSettings.name) {
      case '/':
        return MaterialPageRoute(
          builder: (context) => BlocProvider.value(
            value: _localBloc,
            child: Home(),
          ),
        );
      case '/page1':
        return MaterialPageRoute(
          builder: (context) => BlocProvider.value(
            value: _localBloc,
            child: Page1(),
          ),
        );
      case '/page2':
        return MaterialPageRoute(
          builder: (context) => BlocProvider.value(
            value: _localBloc,
            child: Pag2(),
          ),
        );
    }
  }
}

Then in your main.dart file Add onGenerateRoute

final AppRouter _appRouter = AppRouter();

MaterialApp(
  title: 'My App',
  onGenerateRoute: _appRouter.onGenerateRoute,
),),

In your navigation, you can do this:

Navigator.of(context).pushNamed('/page1');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pythondev0101