flutterflutter-navigation

Flutter AppBar that always stays no matter what


AIM: I wish to make my flutter app also on the web, hence, like most websites, I want it to have an AppBar that is always there no matter how many screens (routes) I push or where I navigate.

PROBLEM: However, when I do Navigator.push(), the AppBar disappears, since a new Scaffold is created with it's own AppBar.

QUESTION: Is there any way to achieve a constant AppBar in my flutter app?

WHAT I TRIED: I tried using IndexedStack, which worked for my main screens. However, when I want to navigate from one of my main screens (which are in the indexed stack), this approach fails.


Solution

  • You should try with go_router which has a shell route and gives you opportunities to keep the app bar always there like a web app please check the given example.

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp.router(
          routerConfig: _router,
        );
      }
    }
    
    final GoRouter _router = GoRouter(
      initialLocation: '/home',
      routes: [
        ShellRoute(
          builder: (context, state, child) {
            return Scaffold(
              appBar: AppBar(title: Text('Shell Route Example')),
              drawer: Drawer(
                child: ListView(
                  padding: EdgeInsets.zero,
                  children: <Widget>[
                     const DrawerHeader(
                      decoration: BoxDecoration(
                        color: Colors.blue,
                      ),
                      child: Text('Navigation Drawer'),
                    ),
                    ListTile(
                      title: Text('Home'),
                      onTap: () {
                        context.pop();
                        context.go('/home');
    
                      },
                    ),
                    ListTile(
                      title: Text('Settings'),
                      onTap: () {
                        context.pop();
                        context.go('/settings');
                      },
                    ),
                  ],
                ),
              ),
              body: child,
            );
          },
          routes: [
            GoRoute(
              path: '/home',
              builder: (context, state) => HomeScreen(),
            ),
            GoRoute(
              path: '/settings',
              builder: (context, state) => SettingsScreen(),
            ),
          ],
        ),
      ],
    );
    
    class HomeScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Center(child: Text('Home Screen'));
      }
    }
    
    class SettingsScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Center(child: Text('Settings Screen'));
      }
    }