Flutter: Introducing `RoutedWidgetSwitcher`

We’ve recently released a new package for use with all “Nav 2” implementations, called routed_widget_switcher: https://pub.dev/packages/routed_widget_switcher

It allows you to declaratively switch child widgets based on the current Router location:

class SideBar extends StatelessWidget {
    Widget build(_){
     return RoutedSwitcher(
        builders: (info) => [
            Routed('*', MainMenu.new),
            Routed('/dashboard', DashboardMenu.new),
            Routed('/settings', SettingsMenu.new),
        ]);
    }
}

RoutedWidgetSwitcher is intended as a complimentary package for any Router (aka Nav2) implementation, including popular routing solutions like GoRouter, RouteMaster or VRouter etc. It is read-only, and simply binds to the current Router location and renders the matching widget.

Switching widgets based on location is useful for two primary use cases:

  • when you have scaffolding around your Navigator, like a SideBar or a TitleBar and you would like it to react to location changes
  • when multiple paths resolve to the same Page and you want to move subsequent routing further down the tree

It is based on Flutters AnimatedSwitcher widget, so it has support for a custom transition and duration. For path matching it uses the popular PathToRegExp package which is also used by many of the implementations including GoRouter and VRouter.

Using RoutedWidgetSwitcher provides a few benefits to your code:

  • no need to add pattern matching logic to your outer scaffolding and inner sub-tree. Instead express the location bindings in a simple declarative format which is more flutter-like
  • Decouple your ui from any particular routing package, making it easier to change packages later or migrate code across projects

You can see an example of it being used with some different router implementations here: https://github.com/gskinnerTeam/flutter-routed-widget-switcher/blob/master/example/lib/main.dart

If you have any questions or comments let us know below!

shawn.blais

Shawn has worked as programmer and product designer for over 20 years, shipping several games on Steam and Playstation and dozens of apps on mobile. He has extensive programming experience with Dart, C#, ActionScript, SQL, PHP and Javascript and a deep proficiency with motion graphics and UX design. Shawn is currently the Technical Director for gskinner.

@tree_fortress

Leave a Reply

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