0

I am using the go_router package in my Flutter application to handle navigation, along with a Bottom Navigation Bar. The navigation works correctly, but I'm facing an issue with the Bottom Navigation Bar not updating the selected screen when navigating through the app.

Here's the scenario: When I tap on the Home screen, it displays the Home screen properly. In the Home screen, I have a button to navigate to the Users screen, and the Users screen has a button to navigate back to the Home screen. However, when I'm on the Users screen and use the button to go back to the Home screen, the Bottom Navigation Bar doesn't reflect that I'm on the Home screen again.

For instance, if I tap on the Settings navigation item, it correctly takes me to the Settings screen. But when I press the button to go back to the Home screen, the Bottom Navigation Bar still shows the Settings screen as selected, instead of updating to the Home screen.

I would like the Bottom Navigation Bar to update and reflect the current screen when navigating using the provided buttons or app bar buttons. Can someone please guide me on how to solve this issue and make the Bottom Navigation Bar update accordingly? Any help or suggestions would be greatly appreciated. Thank you!

main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:servicerider/home_screen.dart';
import 'package:servicerider/settings_screen.dart';
import 'package:servicerider/user_screen.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final router = GoRouter(
    routes: [
      GoRoute(
        path: '/',
        pageBuilder: (context, state) => MaterialPage(
          key: state.pageKey,
          child: const HomeScreen(),
        ),
        routes: [
          GoRoute(
            path: 'user',
            pageBuilder: (context, state) => MaterialPage(
              key: state.pageKey,
              child: const UserScreen(),
            ),
          ),
        ],
      ),
      GoRoute(
          path: '/settings',
          pageBuilder: (context, state) => MaterialPage(
                key: state.pageKey,
                child: const SettingsScreen(),
              )),
    ],
    errorPageBuilder: ((context, state) => MaterialPage(
          key: state.pageKey,
          child: Scaffold(
            body: Center(
              child: Text(state.error.toString()),
            ),
          ),
        )),
  );

  int _selectedIndex =
      0; // Track the selected index of the bottom navigation bar

  // Handle bottom navigation bar item selection
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
      switch (index) {
        case 0:
          router.go('/');
          break;
        case 1:
          router.go('/settings');
          break;
        default:
          break;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      // routeInformationParser: router.routeInformationParser,
      // routerDelegate: router.routerDelegate,
      routerConfig: router,
      title: 'Your App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      builder: (context, router) {
        return Overlay(
          initialEntries: [
            OverlayEntry(builder: (context) {
              return Scaffold(
                appBar: AppBar(
                  title: const Text('Your App'),
                ),
                body: router, // Show the selected page
                bottomNavigationBar: BottomNavigationBar(
                  currentIndex: _selectedIndex,
                  onTap: _onItemTapped,
                  items: const [
                    BottomNavigationBarItem(
                      icon: Icon(Icons.home),
                      label: 'Home',
                    ),
                    BottomNavigationBarItem(
                      icon: Icon(Icons.settings),
                      label: 'Settings',
                    ),
                  ],
                ),
              );
            }),
          ],
        );
      },
    );
  }
}

users_screen.dart

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class UserScreen extends StatefulWidget {
  const UserScreen({super.key});

  @override
  State<UserScreen> createState() => _UserScreenState();
}

class _UserScreenState extends State<UserScreen> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          ElevatedButton(
            onPressed: () => context.go('/'),
            child: const Text('Go to the Home screen'),
          ),
          const Text('user screen'),
        ],
      ),
    );
  }
}

home_screen.dart

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          ElevatedButton(
            onPressed: () => GoRouter.of(context).go('/user'),
            child: const Text('Go to the user screen'),
          ),
          const Text('home screen'),
        ],
      ),
    );
  }
}

settings_screen.dart

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      children: [
        ElevatedButton(
          onPressed: () => context.go('/'),
          child: const Text('Go to the Home screen'),
        ),
        const Text('Settings screen'),
      ],
    ));
  }
}
seddka
  • 105
  • 12

0 Answers0