How to navigate to another page on load in Flutter

7,248

You need to either use a ternary in the onTap if you're using the settings button or, if you just want it to automatically send the user to the correct page when the app starts, you can put the ternary in the MyApp build method.

If you are using the settings button and just want it to pop back to the previous page if the person is not logged in then you can change NotLoggedIn() to a pop.

For some strange reason SO is refusing to post the code when it is properly formatted with four spaces, exactly as it asks, so I'm just going to make a gist.

https://gist.github.com/ScottS2017/3288c7e7e9a014430e56dd6be4c259ab

Share:
7,248
Edmore M Gonese Digolodollarz
Author by

Edmore M Gonese Digolodollarz

BY DAY: I write code for my workplace BY NIGHT: I sleep. Man I love that stuff! My day starts at 0400 hrs and ends at 0600hrs. In between, I'm just waiting

Updated on December 07, 2022

Comments

  • Edmore M Gonese Digolodollarz
    Edmore M Gonese Digolodollarz over 1 year

    I want to navigate to the login page if there is no logged in user, otherwise display the homepage. I thought of calling Navigator.of(context).push() conditionally inside the build method but that triggers an exception. Is there some method I'm missing that I can override?

    Update to add the Homepage widget

    class HomePage extends StatelessWidget {
    final AppUser user;
    
    const HomePage({Key key, this.user}) : super(key: key);
    
    @override
    Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Rera Farm'),
          actions: <Widget>[
            PopupMenuButton(
              itemBuilder: (BuildContext context) {
                return <PopupMenuEntry>[
                  PopupMenuItem(
                    child: ListTile(
                      title: Text('Settings'),
                      onTap: () {
                        Navigator.pop(context);
                        Navigator.push(context,
                            MaterialPageRoute(builder: (BuildContext context) 
                          => SettingsPage()
                        ));
                      },
                    ),
                  ),
                ];
              },
            )
          ],
        ),
        body: _buildBody(context));
    }
    

    And the container

    class HomePageContainer extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
     return new StoreConnector<AppState, _ViewModel>(
       converter: _ViewModel.fromStore,
       builder: (BuildContext context, _ViewModel vm) {
         return HomePage(
          user: vm.user,
         );
       },
     );
     }
    }