Home > OS >  Flutter Login -> HomePage -> Logout problem
Flutter Login -> HomePage -> Logout problem

Time:12-17

I am trying to create a Login Page with a function to check if username and password is correct, if so, navigate to HomePage, on the other hand, show an alert. Problem arises after navigated to HomePage, then logout and return to Login Page, when the alert screen pops up upon login failed, pressed the Dismiss button, then the app crashes with exception:

The following _CastError was thrown while handling a gesture: Null check operator used on a null value

Here are my codes:

Login Page:

void checkValidLogin(context, _username, _password) async {
  bool response = false;
  await Future.delayed(Duration(seconds: 1), (){
    if (_username.toUpperCase() == 'TONY' && _password == '888') {
      response = true;
    };
  });
  if (response == true) {
    //Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => homePage()));
    Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => homePage()));
  }else{
    showMessage(context, 'Login Fail', 'Invalid Username/Password!');
  };
}

Home Page:

IconButton(
            icon: Icon(
              Icons.logout,
              color: Colors.white,
            ),
            onPressed: (){
              Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => MyApp()));
            },
          ),

Show Alert:

void showMessage(context, _title, _content) {
  showPlatformDialog(
    context: context,
    builder: (_) => BasicDialogAlert(
      title: Text(_title),
      content:
      Text(_content),
      actions: <Widget>[
        BasicDialogAction(
          title: Text("Dismiss"),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ],
    ),
  );
}

CodePudding user response:

_CastError was thrown while handling a gesture: Null check operator used on a null value generally is thrown when you are trying to use context of a deactivated widget.

In your case, the problem in the following line:

Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => MyApp()));

You are navigating to MyApp which contains MaterialApp, so there will be two MaterialApps, because of which the Navigator works incorrectly. Later when you click "Dismiss" button Navigator.pop(context) is poping the LoginPage onstead of closing the dialog box. When you press the button again, it tries to use context of the deactivated LoginPage and the error is thrown.

Therefore, you have to update the function of IconButton:

IconButton(
        icon: Icon(
          Icons.logout,
          color: Colors.white,
        ),
        onPressed: (){
          Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => LoginPage()));
        },
      ),
  • Related