How to dispose statefulShellRoute

276 Views Asked by At

I'm using StatefulShellRoute, which is one of the features of the Go Router package in Flutter. I've searched a lot, but couldn't find a solution for the following problem: Routes using StatefulShellRoute are never disposed after initialization.

My config routes:

final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');

/// GoRouter configuration
static final router = GoRouter(
    initialLocation: splash,
    observers: [
      routeObserver,
      FirebaseAnalyticsObserver(analytics: AppAnalytics.instance),
    ],
    navigatorKey: _rootNavigatorKey,
    routes: <RouteBase>[
      StatefulShellRoute.indexedStack(
          builder: (context, state, navigationShell) => BottomNavigation(navigationShell: navigationShell),
          branches: <StatefulShellBranch>[
            StatefulShellBranch(
              routes: <RouteBase>[
                GoRoute(
                  name: home,
                  path: home,
                  pageBuilder: (context, state) => _transitionPageBuilder(context, state, const HomePage()),
                ),
              ],
            ),
            StatefulShellBranch(
              routes: <RouteBase>[
                GoRoute(
                  name: history,
                  path: history,
                  pageBuilder: (context, state) => _transitionPageBuilder(context, state, const HistoryPage()),
                ),
              ],
            ),
    ],
    debugLogDiagnostics: true
);

When I click on the back button, I expect the dispose of the page I'm on to be called, but it doesn't happen! I used WillPopScop widget to handle exit app. My logic of handle back button like this:

  DateTime? _previousDateTime;
  Future<bool> willPopScope(DateTime currentDateTime) {
    if (_previousDateTime == null || currentDateTime.difference(_previousDateTime!) > const Duration(seconds: 2)) {
      _previousDateTime = currentDateTime;
      _showToastMessage.sink.add('Press again to exit application');
      return Future.value(false);
    }
    if (Platform.isAndroid) {
      SystemNavigator.pop();
      dispose();
    } else {
      SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }
   // This Future return not work for Go router!
    return Future.value(true);
  }

My question is: How to call dispose method (that is in StatefulWidget) for routes are StatefulShellRoute?

Tip: Memory leak will be happen if you didn't dispose of your streams.

0

There are 0 best solutions below