Как добавить ошибку «этот пользователь / учетная запись не существует» в Flutter, используя Firebase?

#firebase #flutter #firebase-authentication

# #firebase #flutter #firebase-аутентификация

Вопрос:

Я пытаюсь создать страницу входа в Flutter. Я также использовал Firebase для аутентификации пользователя и входа в систему. Проблема в том, что, хотя я могу успешно войти в систему с правильной информацией, я не могу отобразить что-либо вроде всплывающего окна с ошибкой или сообщения о том, что учетная запись не существует. Это мой код :

 class _LoginPageState extends State<LoginPage> {
  String _email, _password;
  final auth = FirebaseAuth.instance;
  bool hidepwd = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: Container(
          margin: EdgeInsets.all(5),
          width: 50,
          height: 50,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(10)),
            color: Color(0xffe9eefa),
          ),
          child: IconButton(
            onPressed: (){Navigator.pop(context);},
            icon: Icon(
              Icons.keyboard_arrow_left_rounded,
              color: Color(0xff2657ce),
            ),
          ),
        ),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            child: IconButton(
              icon: Icon(
                Icons.account_circle_rounded,
                color: Color(0xff2657ce),
                size:100,
              ),
            ),
          ),
          SizedBox(height: 50,),
          Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 25.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(right: 240),
                        child: Text('Email Address', style: TextStyle(
                          fontSize: 15,),),
                      ),
                      SizedBox(height: 10,),
                      Container(
                        padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(20)),
                          color: Colors.grey.withOpacity(0.2),
                        ),
                        child: TextFormField(
                          keyboardType: TextInputType.emailAddress,
                          decoration: InputDecoration(
                              hintText: 'Email',
                          ),
                          onChanged: (value) {
                            setState(() {
                              _email = value.trim();
                            });
                          },
                        ),
                      ),
                      SizedBox(height: 20,),
                      Container(
                        padding: EdgeInsets.only(right: 270),
                        child: Text('Password', style: TextStyle(
                          fontSize: 15,
                        ),),
                      ),
                      SizedBox(height: 10,),
                      Container(
                        padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(20)),
                          color: Colors.grey.withOpacity(0.2),
                        ),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: TextFormField(
                                obscureText: hidepwd,
                                decoration: InputDecoration(hintText: 'Password'),
                                onChanged: (value) {
                                  setState(() {
                                    _password = value.trim();
                                  });
                                },
                              ),
                            ),
                            Container(
                              height: 50,
                              width: 50,
                              child: IconButton(
                                onPressed: togglepwdVisibility,
                                icon: IconButton(
                                  icon: hidepwd == true ? Icon(
                                      Icons.visibility_off
                                  ): Icon(Icons.visibility),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 20,),

                      RaisedButton(
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
                          color: Color(0xff5178D7),
                          child: Text("Log In", style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.w600,
                              fontSize: 15
                          ),),
                          onPressed: (){
                            auth.signInWithEmailAndPassword(email: _email, password: _password).then((_){
                              Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => frontpage()));
                            });
                          }
                          ),
                      SizedBox(height: 20,),
                      Container(
                        child: Center(
                          child: Text('---- or ----'),
                        ),
                      ),
                      SizedBox(height: 20,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text("Don't have an account? "),
                          InkWell(
                            onTap: openSignUpPage,
                            child: Text("Sign Up", style: TextStyle(
                                color: Color(0xff1A3C90),
                                fontWeight: FontWeight.w700
                            ),),
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ),
        ],
      ),
    );
  }
 

Любые идеи / предложения о том, что я мог бы добавить или изменить в своем коде, чтобы включить это сообщение об ошибке, когда я не могу войти в систему в целом?

Ответ №1:

В вашем логине onPressed: (){ ... } поймайте FirebaseAuthException .

Источник: https://firebase.flutter.dev/docs/auth/usage/#sign-in

 try {
  UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: "barry.allen@example.com",
    password: "SuperSecretPassword!"
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'user-not-found') {
    print('No user found for that email.');
  } else if (e.code == 'wrong-password') {
    print('Wrong password provided for that user.');
  }
}
 

Комментарии:

1. В нем говорится: «Выражение ожидания может использоваться только в асинхронной функции»..

2. @walr0s использует это onPressed: () async { ... }

Ответ №2:

Если вам нужно, чтобы при каждой ошибке входа в систему появлялись предупреждения, вы можете попробовать использовать следующую функцию, но только если вы используете TextEdittingController:

 signIn() async {
    if (_loginFormKey.currentState!.validate()) {
      _loginFormKey.currentState!.save();
      try {
        await FirebaseAuth.instance
            .signInWithEmailAndPassword(
                email: _emailController.text,
                password: _passwordController.text)
            .then((currentUser) => FirebaseFirestore.instance
                .collection("users")
                .doc(currentUser.user!.uid)
                .get()
                .then((conext) => Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => HomePage())))
                .catchError((err) => print(err)));
      } on FirebaseAuthException catch (error) {
        if (error.code == 'user-not-found') {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text("Auth Exception!"),
                  content: Text("This User Does Not Exist."),
                  actions: <Widget>[
                    Row(
                      children: [
                        ElevatedButton(
                          child: Text("Sign In Again"),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                    )
                  ],
                );
              });
        } else if (error.code == 'wrong-password') {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text("Auth Exception!"),
                  content: Text("The Password Entered is Invalid."),
                  actions: <Widget>[
                    Row(
                      children: [
                        ElevatedButton(
                          child: Text("Sign In Again"),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                    )
                  ],
                );
              });
        }
      }
    }
  }