Using named Navigator from different widgets in flutter?

Viewed 793

I need to navigate to a widget(screen) using named navigation from another widget(screen). This is the body of MyHomePage Widget

body: Navigator(
  key: _navigatorKey,
  initialRoute: '/',
  onGenerateRoute: (RouteSettings settings) {
    WidgetBuilder builder;

    switch (settings.name) {
      case '/':
        builder = (BuildContext context) => UIHomePage();
        break;
      case '/cart':
        builder = (BuildContext context) => UICartPage();
        break;
      case '/account':
        builder = (BuildContext context) => UIAccountPage();
        break;
      default:
        throw Exception('Invalid route: ${settings.name}');
    }

    return MaterialPageRoute(builder: builder, settings: settings, );
  },
),

I can toggle these PageRoutes from the bottomNavigationBar with _navigatorKey.currentState.pushNamed(routeNames[tabItem]) where routeNames is a list of Strings ['/', '/cart', '/account']. This works fine.

Now, from UIAccountPage(), where I have a ListTile named 'Cart', I wish to navigate to the UICartPage on tapping that particular tile. I also have several other tiles that I wish to use to navigate to other widgets (screens).

To achieve this, do I have to expand the onGenerateRoute in MyHomePage to accommodate other routes or I have to create another custom Navigator somewhere? I am at odds. If somebody could guide with a simple illustration that would be awesome.

Thanks

Edit: Also I have no idea what setting does in Navigator and _navigatorKey is final _navigatorKey = GlobalKey<NavigatorState>()

2 Answers

i'm pretty new using Flutter but i've this implementation an works fine for routes.

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Temp Detector',
      initialRoute: '/',
      routes: {
        '/': (context) => AuthScreen(),
        '/register': (context) => SignInScreen(),
        '/login': (context) => LoginScreen(),
        '/home': (context) => HomeScreen(),
        '/config': (context) => ConfigScreen(),
      },
    );
  }
}

And when i try to go to another view i use:

Navigator.pushReplacementNamed(context, '/home');

Where the 2nd param is the name defined in the routes.

Hope it does help you!

1, I think you should be try BottomNavigationBar with PageView or TabView.

2, With your issue, you can try options create a callback for UIAccountPage:

  case '/account':
    builder = (BuildContext context) => UIAccountPage(onTapCart: () {
      _navigatorKey.currentState.pushNamed('/cart');
    });
    break;

And UIAccountPage

class UIAccountPage extends StatelessWidget {

  VoidCallback onTapCart;

  UIAccountPage({this.onTapCart});

  @override
  Widget build(BuildContext context) {
    .....
  }

}
Related