简体   繁体   中英

Display error message instead of throw exception in console (Flutter Firebase)

How to show the error message when the user enters the incorrect username and password? Can I display a message when there are multiple conditions in authenticating the user? The message should show on the screen instead of throwing the exception in the console.

The exception I get in the console The exception has occurred. PlatformException (PlatformException(firebase_auth, com.google.firebase.auth.FirebaseAuthInvalidUserException: There is no user record corresponding to this identifier. The user may have been deleted., {code: user-not-found, additionalData: {}, message: There is no user record corresponding to this identifier. The user may have been deleted.}, null))

import 'package:firebase_auth/firebase_auth.dart';

abstract class BaseAuth {
  Future<String> currentUser();
  Future<String> signIn(String email, String password);
  Future<String> createUser(String email, String password);
  Future<void> signOut();
}

class Auth implements BaseAuth {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  Future<String> signIn(String email, String password) async {
    UserCredential result = await FirebaseAuth.instance
        .signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
    return user.uid;
  }

  Future<String> createUser(String email, String password) async {
    UserCredential result = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(email: email, password: password);
    User user = result.user;
    return user.uid;
  }


  Future<String> currentUser() async {
    User user = _firebaseAuth.currentUser;
    return user != null ? user.uid : null;
  }

  Future<void> signOut() async {
    return _firebaseAuth.signOut();
  }
}

A simple try catch would do the trick

Future<String> signIn(String email, String password) async {
try{
    UserCredential result = await FirebaseAuth.instance
        .signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
    return user.uid;
}on AuthException catch(error){
return Future.error(error);
  }
}

Now on how to handle the error in the UI assuming you know the basics:D

await signIn(email,password).then((onSuccess){
 //do something with data or not up to you
 }).catchError((err){
 print(err);
 });

Hope it helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM