Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To incorporate restorable push navigation with the get package in Flutter, you can follow the following steps:

  1. Add the get package to your project by adding the following line to your pubspec.yaml file:
dependencies:
  get: ^4.1.4
  1. Create a custom navigator that handles the restorable navigation. This can be done by creating a new class that extends the Navigator class and overrides the push and pushReplacement methods:
class RestorableNavigator extends Navigator {
  RestorableNavigator({
    required GlobalKey<NavigatorState> key,
    required List<Route<dynamic>> pages,
    required this.restorationId,
    RoutePredicate? onPopPage,
  }) : super(
          key: key,
          pages: pages,
          onPopPage: onPopPage,
        );

  final String restorationId;

  @override
  void didUpdateWidget(Navigator oldWidget) {
    super.didUpdateWidget(oldWidget);
    this.restorationId = oldWidget.restorationId;
  }

  @override
  Route push(Route route) {
    route = MaterialPageRoute(
      builder: route.builder,
      settings: RouteSettings(
        name: route.settings.name,
        isInitialRoute: pages.isEmpty,
      ),
    );
    return super.push(route);
  }

  @override
  Route pushReplacement(Route route, {Object? result}) {
    route = MaterialPageRoute(
      builder: route.builder,
      settings: RouteSettings(
        name: route.settings.name,
        isInitialRoute: pages.isEmpty,
      ),
    );
    return super.pushReplacement(route, result: result);
  }
}
  1. Create a RestorationScope widget that wraps your app and provides a unique restoration ID:
RestorationScope(
  restorationId: 'main',
  child: MaterialApp(
    // ...
  ),
)
  1. Use the Navigator.restorablePush and Navigator.restorablePushReplacement methods provided by the get package to navigate to new screens:
Navigator.restorablePush(
  context,
  MaterialPageRoute(builder: (context) => MyNewPage()),
)
Navigator.restorablePushReplacement(
  context,
  MaterialPageRoute(builder: (context) => MyNewPage()),
)

The get package will automatically handle saving and restoring the navigation history, so your users can pick up where they left off even if they close and reopen your app.