Wrapping Routes


In the last page, we created a BooksRouter and AccountRouter to handle their respective routes via nested routes. We can take this example one step further by wrapping our nested routes with other widgets.

For example, we might want to wrap our BooksRouter with a state management solution. By doing so, we can scope our state to only books routes instead of lifting state up above our main AppRouter .

In this example, we'll wrap our BooksRouter with a cubit, scaffold and app bar , and scope it to just books routes. Let's start by creating the BooksWrapperPage class.
class BookWrapperPage extends StatelessWidget {
  const BookWrapperPage({Key key}) : super(key: key);

  
  Widget build(BuildContext context) { 
    return Scaffold(
      appBar: BooksAppBar(),
      body: BlocProvider(
        create: (context) => BooksCubit(),
        child: AutoRouter(), // The AutoRouter() widget used here
        // is required to render sub-routes
      ),
    );
  }
}
Now, we just need to insert our BooksWrapperPage into the BooksRouter
...
AutoRoute(
    path: "/books",
    name: "BooksRouter",
    page: BooksWrapperPage, // We replace EmptyRouterPage with our
    // BooksWrapperPage now!
    children: [
        AutoRoute(path: '', page: BooksPage),
        AutoRoute(path: 'details', page: BookDetailsPage),
        RedirectRoute(path: '*', redirectTo: ''),
    ],
),
...

And that's it! Now, all of your books sub-routes will be wrapped by our BooksCubit , Scaffold , and BooksAppBar . To see a visual representation of what is happening, check out the image below: