Skip to main content

Overview

ConditionalRouteWidget is a widget that conditionally applies a builder function based on whether the current route matches certain criteria. This is useful for applying route-specific styling, wrapping widgets differently on certain pages, or implementing route-based behavior.

Constructor

const ConditionalRouteWidget({
  Key? key,
  List<String>? routes,
  List<String>? routesExcluded,
  required TransitionBuilder builder,
  required Widget child,
})
routes
List<String>?
List of route names to include. If provided, the builder is applied only when the current route is in this list. Cannot be used together with routesExcluded.
routesExcluded
List<String>?
List of route names to exclude. If provided, the builder is applied only when the current route is NOT in this list. Cannot be used together with routes.
builder
TransitionBuilder
required
Builder function to apply when the condition is met. Receives the BuildContext and child widget.
child
Widget
required
The child widget to conditionally wrap.

Usage

Apply styling to specific routes

ConditionalRouteWidget(
  routes: ['/home', '/profile'],
  builder: (context, child) {
    return Container(
      color: Colors.blue.shade50,
      child: child,
    );
  },
  child: MyContent(),
)

Exclude routes from styling

ConditionalRouteWidget(
  routesExcluded: ['/login', '/signup'],
  builder: (context, child) {
    return SafeArea(
      child: child,
    );
  },
  child: MyApp(),
)

Apply navigation bar to most routes

ConditionalRouteWidget(
  routesExcluded: ['/splash', '/onboarding'],
  builder: (context, child) {
    return Scaffold(
      body: child,
      bottomNavigationBar: MyNavigationBar(),
    );
  },
  child: currentPage,
)

How it works

The widget checks the current route using ModalRoute.of(context)?.settings.name and applies the builder function only when the route matches the specified conditions:
  • If routes is provided, the builder is applied when the current route is in the list
  • If routesExcluded is provided, the builder is applied when the current route is NOT in the list
  • If neither condition is met, the child is returned without modification
You cannot provide both routes and routesExcluded at the same time. Choose one approach based on your use case.

Common use cases

Route-specific layouts

Apply different layouts or containers to specific routes

Conditional navigation bars

Show or hide navigation elements on certain pages

Safe area handling

Apply SafeArea only to routes that need it

Theme variations

Apply different themes or styling to specific route groups

Build docs developers (and LLMs) love