Flutter Firebase登录时user-not-found错误无法被try-catch捕获
问题解决:try-catch无法捕获Firebase Auth的user-not-found错误
核心问题是你没有等待异步操作完成,导致signInWithEmailAndPassword抛出的错误无法被try-catch捕获,同时print("UC = ")会被提前执行。
错误原因
FirebaseAuth.instance.signInWithEmailAndPassword()是异步方法,返回Future<UserCredential>。你当前的代码没有用await修饰这个调用,所以程序不会等待登录请求完成,直接执行后续的print语句;而异步操作抛出的错误会在后台变成未处理异常,根本进入不了try-catch块。
修正后的代码
TextButton( onPressed: () async { final email = _eMail.text; final password = _passWord.text; try { // 添加await等待异步操作完成 final userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword( email: email, password: password, ); print("UC = "); print(userCredential); } catch (e) { print("Error Code: "); print(e.runtimeType); print(e); } }, child: Text("Login"), ),
修正后效果
添加await后,程序会等待登录请求执行完成:
- 若登录成功,才会执行后续的print语句;
- 若抛出
user-not-found或其他错误,会被try-catch捕获,进入catch块打印错误信息,不会执行print("UC = ")。
内容的提问来源于stack exchange,提问作者Anshumaan Mishra
相关产品推荐
相关产品推荐

