3
votes

I am trying to navigate to my home page or login page on the basis of authStatus. While using Navigator.of(context)... it returns null on the build method for a second and then screen refreshes and navigate to the given page successfully. I am relatively new to mobile development and flutter. Any leads will help! Thanks.

Here is the code:

  @override
  Widget build(BuildContext context) {
    switch (authStatus) {
      case AuthStatus.NOT_LOGGED_IN:
        WidgetsBinding.instance.addPostFrameCallback((_) {
          {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => LoginSignUpPage(
                        auth: widget.auth,
                        onSignedIn: _onLoggedIn,
                        params: widget.params,
                      )),
            );
          }
        });

        break;
      case AuthStatus.LOGGED_IN:
        if (_userId.length > 0 && _userId != null) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => HomePage(
                        userId: _userId,
                        auth: widget.auth,
                        onSignedOut: _onSignedOut,
                        params: widget.params,
                      )),
            );
          });
        } else
          return widget.waitingScreen;
        break;
      default:
        return widget.waitingScreen;
    }

Here is the error :

A build function returned null. The offending widget is: RootPage Build functions must never return null. To return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".

1
the switchCase doesn't actually return anything in the first case and the second only if enters the else, you should do this operation somewhere else and not the build method (init or didChangeDependencies) - EdwynZN
Hey, switch case does work! I have set the auth status in initstate and didChangeDependencies method but the issue is with the Navigator.push statement. I guess before it returns the view, build method executes asynchronously and gives a null error and just when Navigator.push get executed it load the correct view. - Maaz Ahmed
you see the error for a second because you're pushing a new page in front of that (it runs async because you added WidgetsBinding.instance.addPostFrameCallback) but your rootPage build method never returns a Widget - EdwynZN

1 Answers

4
votes

on the code line following WidgetsBinding, add

return Container();

You could also include a color parameter to match your design.