Flutter Widget Router

Manages opening and closing pages in an application.

Key Components:


void main() {

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerDelegate: CustomRouterDelegate(),
      routeInformationParser: CustomRouteInformationParser(),

Information Parser:

class CustomRouteInformationParser 
	extends RouteInformationParser<String> {
  Future<String> parseRouteInformation(
	  RouteInformation routeInformation) async {
    // You can customize the parsing logic here.
    // For now, we'll just use the route location directly.
    return routeInformation.location ?? '/';

  RouteInformation restoreRouteInformation(String path) {
    return RouteInformation(location: path);

Router Delegate:

class CustomRouterDelegate extends RouterDelegate<String>
    with ChangeNotifier, 
         PopNavigatorRouterDelegateMixin<String> {
  String _currentPath = '/';

  GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  String get currentConfiguration => _currentPath;

  Future<void> setNewRoutePath(String path) async {
    _currentPath = path;

  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: [
	        child: HomePage(), 
	        key: ValueKey('Home')),
        if (_currentPath == '/details') 
		        child: DetailsPage(), 
		        key: ValueKey('Details')),
      onPopPage: (route, result) {
        if (!route.didPop(result)) return false;
        // Update the current path when a route is popped
        _currentPath = '/';
        return true;

In this demo, CustomRouteInformationParser parses the route information into a String. The CustomRouterDelegate then uses this string to determine which page to display. The HomePage includes a button to navigate to the DetailsPage, and the Navigator in the RouterDelegate is used to manage the stack of pages.

This is a basic example. In a real-world application, you would likely have more complex route parsing and handling logic.

Architectural Design

An application can have zero, one, or many Router widgets, depending on its needs.

No Router:

Multiple Routers:

State Restoration

Capable of restoring the current configuration after app restarts.


本文链接:Flutter Widget Router

版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!