Flutter auto_route | How do I wrap a route with BlocProvider?

Issue

So, I’m using the auto_route package for navigation in my app and flutter_bloc for state management. When I was using the old Navigator, I could just wrap a route with a BlocProvider. For example:

class Router {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(
          builder: (_) => BlocProvider( // wrapped Home with BlocProvider
            create: (context) => SubjectBloc(),
            child: Home(),
          ),
        );
      case '/feed':
        return MaterialPageRoute(builder: (_) => Feed());
    }
  }
}

Now, auto_route uses annotations to generate a routing file. How would I go around providing provider context to the route?

Solution

We have our page widget (state/less/ful) implement AutoRouteWrapper

class HomePage extends StatelessWidget implements AutoRouteWrapper{
  .....
 @override
 Widget wrappedRoute(context){
   return BlocProvider(
            create: (context) => HomeBloc(),
            child:  this, // this as the child Important!
          );
   }

}

Answered By – IncorrectMouse

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *