Flutter - How to implement a bottom navigation bar with named routes?

Viewed 1039

I wanted to implement a bottom navigation bar with named routes. It seems the view keeps refreshing, getting stuck and when I tap the bottom navigation tabs, they are not working with my code.

final _navigatorKey = GlobalKey<NavigatorState>();
  int currentIndex = 0;
  List<String> _pages = <String>[
    Routes.startupViewRoute,
    Routes.startupViewRoute,
    Routes.startupViewRoute,
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Navigator(
        key: _navigatorKey,
        initialRoute: Routes.startupViewRoute,
        onGenerateRoute: Router().onGenerateRoute,
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        onTap: (index) {
          _navigatorKey.currentState.pushNamed(_pages[index]);
        },
        items: [
          BottomNavigationBarItem(
            icon: new Icon(Icons.home),
            title: new Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: new Icon(Icons.person),
            title: new Text('Profile'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            title: Text('Settings'),
          )
        ],
      ),
    );
1 Answers

Definitely using Route name is more comfortable. it has few steps. 1. at the screen you want to navigate to add a final variable that hold the route for ex. static const routeName = '/pageName'; (the / is important)

  1. at the main page you need to add: PageName.routeName:(ctx)=>PageName(),

  2. where you want to redirect to the new page add: Navigator.of(ctx).pushNamed(PageName.routeName); you can also pass argument through it.

Related