Как отобразить оповещение об ошибках аутентификации firebase

#firebase #flutter #dart

# #firebase #флаттер #dart

Вопрос:

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

Вот мои функции CreateUser и signInUser и моя функция кнопки регистрации

   Future registerWithEmailAndPassword({String email,password,username,image,phoneNumber}) async {
    try {
      UserCredential userCredential = await _firebaseAuth
          .createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        print('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');
      }
    } catch (e) {
      print(e);
    }
  }
 
  Future signInWithEmailAndPassword({String email, String password}) async {
    try {
      UserCredential userCredential = await _firebaseAuth
          .signInWithEmailAndPassword(
          email: email,
          password: password
      );
      User user = userCredential.user;
      assert(user.uid != null);
      email = user.email;
    } 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.');
      }
    }
  }
 
             press: () {
              if (formKey.currentState.validate()) {
                formKey.currentState.save();
                    context
                    .read<Authentication>()
                    .signInWithEmailAndPassword(
                    email: emailController.text,
                    password: passwordController.text)
                    .whenComplete(() => Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) =>
                            HomeScreen())));
              }
            },
 

Ответ №1:

Вы можете настроить AlertDialog виджет, подобный этому. Кнопки «Да» / «Нет», вероятно, излишни в вашей ситуации, и если это так, просто преобразуйте в ok кнопку, и тогда вам не нужно проверять возвращаемый результат.

 Future<String> showYesNoAlertDialog({
  @required BuildContext context,
  @required String titleText,
  @required String messageText,
}) async {
  // set up the buttons
  final Widget yesButton = FlatButton(
    onPressed: () => Navigator.pop(context, 'yes'),
    child: const Text('Yes'),
  );
  final Widget noButton = FlatButton(
    onPressed: () => Navigator.pop(context, 'no'),
    child: const Text('No'),
  );

  // set up the AlertDialog
  final alert = AlertDialog(
    title: Text(titleText),
    content: Text(messageText),
    actions: [
      yesButton,
      noButton,
    ],
  );

  // show the dialog
  return showDialog(
    context: context,
    builder: (context) => alert,
  );
}
 

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

 final dr = await showYesNoAlertDialog(
  context: context,
  titleText: 'Authentication Error',
  messageText:
      'There has been an error during authentication.  Would you like to retry?',
);

if (dr == 'yes') {
  // Yes button clicked
}
else {
  // No button clicked
}
 

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

1. Большое вам спасибо. у меня есть еще один вопрос: «Мое приложение переходит к следующему экрану, даже если в аутентификации firebase есть ошибка» как я могу это остановить?

2. whenComplete() Метод @PetersVictor определяет The [action] function is called when this future completes, whether it does so with a value or with an error. так, что даже его успешный или ошибочный вход в систему всегда будет вызываться. В вашей ситуации после завершения вашего метода signInWithEmailAndPassword() он всегда будет перемещаться на основе вашего кода

3. Спасибо, правление, итак, как мне убедиться, что вход в систему или регистрация прошли успешно, прежде чем перейти на следующую страницу