You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter iOS集成Firebase Phone Auth无法接收验证码求助

Flutter Firebase手机认证收不到验证码(iOS)解决方案

排查步骤与修复建议

1. 修正Firebase初始化顺序

你的main.dart中runApp在Firebase.initializeApp之前执行,会导致Firebase服务初始化不完整,直接影响短信推送逻辑。调整代码顺序并添加必要的绑定初始化:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized(); // 必须添加,确保Flutter引擎绑定完成
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

2. 完善iOS端FCM配置

仅在pubspec.yaml添加依赖还不够,需在Xcode项目中补全FCM集成:

  • 在Info.plist中添加配置,避免代理冲突:
    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
    
  • 修改AppDelegate.swift(Objective-C项目对应调整),集成FCM推送逻辑:
    import UIKit
    import Firebase
    import FirebaseMessaging
    
    @main
    class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            FirebaseApp.configure()
            Messaging.messaging().delegate = self
            
            // 请求推送权限
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
                guard granted else { return }
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
            return true
        }
    
        func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
            print("FCM Token: \(fcmToken ?? "")")
        }
    
        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            Messaging.messaging().apnsToken = deviceToken
        }
    }
    

3. 严格校验手机号码格式

Firebase要求手机号码必须使用E.164国际标准格式(例如+8613xxxxxxxxx),补充格式校验逻辑:

if (emailController.text.isEmpty || phoneController.text.isEmpty) {
  print("Email and phone required!");
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("请输入邮箱和手机号!", style: TextStyle(fontWeight: FontWeight.bold)), backgroundColor: color_bluepurple));
  return;
}
// 校验国际格式前缀
if (!phoneController.text.startsWith("+")) {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("手机号需使用国际格式(例如+8613xxxxxxxxx)!", style: TextStyle(fontWeight: FontWeight.bold)), backgroundColor: color_bluepurple));
  return;
}

4. 补全错误处理逻辑

当前verificationFailed回调仅处理了invalid-phone-number,其他错误(如FCM配置异常、短信配额耗尽)也会导致收不到验证码,需补充完整:

verificationFailed: (FirebaseAuthException e) {
  String errorMsg = "验证失败,请稍后重试";
  switch(e.code) {
    case 'invalid-phone-number':
      errorMsg = "手机号格式不正确";
      break;
    case 'quota-exceeded':
      errorMsg = "短信发送配额已用完";
      break;
    case 'missing-app-token':
      errorMsg = "FCM令牌未获取,请检查推送配置";
      break;
  }
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMsg, style: TextStyle(fontWeight: FontWeight.bold)), backgroundColor: color_bluepurple));
},

5. iOS测试必知

  • 必须使用真实iOS设备测试,模拟器无法接收短信推送;
  • 确保设备网络稳定,Firebase需要可靠网络连接发送验证码;
  • 检查Firebase控制台「身份验证→使用情况」,确认短信发送配额未耗尽。

内容的提问来源于stack exchange,提问作者Kyle Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:35:28