Search code examples
flutterflutter-navigationflutter-go-router

Tapping device's back button, the app closes completely using go_router package


I am using the go_router package to implement routing between screens.

first I navigate from the A screen to the B screen using GoRouter, then when I try to navigate from B to A with the device's back button, the app closes completely instead of navigating back to A.

But, if I use Flutter's default navigator.push, then the navigation works as intended. B to A.

I'm using Flutter version 3.19.3.

Check my code.

Route file

class Routes {
  static const String splash = '/';
  static const String splashName = 'splash';

  static const String dashboard = '/dashboard';
  static const String dashboardName = 'dashboard';

  static GoRouter goRoute = GoRouter(initialLocation: '/', routes: [
    GoRoute(
      path: splash,
      name: splashName,
      builder: (context, state) {
        return const SplashScreen();
      },
    ),
    GoRoute(
      path: dashboard,
      name: dashboardName,
      builder: (context, state) {
        return const DashBoard();
      },
    ),
  ]);
 
}

main.dart File

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized(); 
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ResponsiveSizer(
      builder: (context, orientation, screenType) {
        return BlocProvider(
          create: (_) => TransaltionCubit(),
          child: MaterialApp.router(
            debugShowCheckedModeBanner: false,
            title: AppStrings.appName,
            routerConfig: Routes.goRoute,
          ),
        );
      },
    );
  }
}

Navigate using below code

context.go(RouteNames.dashboard);


Solution

  • instead of using context.go use context.push it doesn't pop A page and make new B page upon previous page. beacuse context.go remove all pages from ther stackTree and push new page but context.push does not pop any page from stackTree.