Flutter集成Firebase Auth遇手机号验证未处理异常求助
Firebase Auth手机号验证异常排查与解决
问题描述
选择国家码并输入手机号后触发未处理异常,错误信息如下:
E/flutter ( 8922): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: 'package:firebase_auth/src/firebase_auth.dart': Failed assertion: line 805 pos 7: 'phoneNumber != null || multiFactorInfo != null': Either phoneNumber or multiFactorInfo must be provided.
问题根源
两处代码错误导致手机号未正确传递给Firebase Auth验证接口:
- 登录页面拼接手机号时引用错误:
sendPhoneNumber方法中,拼接字符串时误用了phoneController(控制器实例)而非phoneNumber(输入的手机号文本),导致传递的是控制器的toString内容而非真实手机号。 - Auth仓库未传入必填参数:调用
auth.verifyPhoneNumber时缺少必填的phoneNumber参数,Firebase无法获取待验证的手机号。
修复步骤
1. 修复登录页面的sendPhoneNumber方法
修改LoginScreen类中的sendPhoneNumber函数,将拼接变量改为phoneNumber:
void sendPhoneNumber() { String phoneNumber = phoneController.text.trim(); if (country != null && phoneNumber.isNotEmpty) { ref .read(authControllerProvider) .signInWithPhone(context, '+${country!.phoneCode}$phoneNumber'); // 替换为phoneNumber变量 } else { showSnackBar(context: context, content: 'Fill out all the fields'); } }
2. 修复Auth仓库的signInWithPhone方法
在AuthRepository类的signInWithPhone方法中,为verifyPhoneNumber添加phoneNumber参数:
void signInWithPhone(BuildContext context, String phoneNumber) async { try { await auth.verifyPhoneNumber( phoneNumber: phoneNumber, // 新增必填参数 verificationCompleted: (PhoneAuthCredential credential) async { await auth.signInWithCredential(credential); }, verificationFailed: (e) { throw Exception(e.message); }, codeSent: ((verificationId, forceResendingToken) async { Navigator.pushNamed( context, OTPScreen.routeName, arguments: verificationId, ); }), codeAutoRetrievalTimeout: (String verificationId) {}, ); } on FirebaseAuthException catch (e) { showSnackBar(context: context, content: e.message!); } }
验证修复
修改完成后重新运行应用,选择国家码并输入手机号,Firebase Auth将正确接收手机号并触发验证码发送流程,异常不再出现。
内容的提问来源于stack exchange,提问作者Jabid Hasan
相关产品推荐
相关产品推荐

