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

如何在Flutter中使用Firebase实现手机认证?

Flutter 中使用 Firebase 实现手机认证的完整流程

别着急,我把Flutter里用Firebase实现手机认证的完整流程一步步给你理清楚,这是我平时开发常用的方案,亲测靠谱:

一、前期准备工作

  • 先给你的Flutter项目添加必要的Firebase依赖,在pubspec.yaml文件里加入:
firebase_core: ^2.15.0
firebase_auth: ^4.10.0

(版本号可以换成当前最新的,不过这两个版本兼容性不错)

  • 打开Firebase控制台,进入你的项目,找到Authentication模块,切换到「登录方法」标签,找到「手机号码」选项并启用它。这里要注意必须配置安卓应用的SHA-1指纹,不然验证码发送会失败;iOS端则需要开启推送权限相关配置。

二、核心代码实现

1. 先初始化Firebase

在你的main.dart里,记得先初始化Firebase再启动App:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化Firebase
  await Firebase.initializeApp();
  runApp(const MyApp());
}

2. 发送验证码到用户手机

创建FirebaseAuth实例,然后调用verifyPhoneNumber方法来触发短信发送:

final FirebaseAuth _auth = FirebaseAuth.instance;
String? _verificationId; // 用来保存验证ID,后续验证验证码要用

// 发送验证码的函数
void _sendVerificationCode(String phoneNumber) async {
  await _auth.verifyPhoneNumber(
    phoneNumber: phoneNumber, // 格式必须带国家代码,比如+86138xxxxxxx
    verificationCompleted: (PhoneAuthCredential credential) async {
      // 部分安卓设备会自动读取短信完成验证,这里直接登录
      await _auth.signInWithCredential(credential);
      print('自动验证登录成功');
      // 这里可以写登录成功后的逻辑,比如跳转到主页
    },
    verificationFailed: (FirebaseAuthException e) {
      // 处理验证失败的情况
      if (e.code == 'invalid-phone-number') {
        print('输入的手机号格式不正确');
      } else {
        print('验证失败:${e.message}');
      }
    },
    codeSent: (String verificationId, int? resendToken) {
      // 验证码发送成功,保存验证ID
      _verificationId = verificationId;
      print('验证码已发送,请注意查收短信');
    },
    codeAutoRetrievalTimeout: (String verificationId) {
      // 自动获取验证码超时,更新验证ID
      _verificationId = verificationId;
    },
    timeout: const Duration(seconds: 60), // 验证码有效期60秒
  );
}

3. 验证用户输入的验证码

用户收到短信输入验证码后,调用这个函数完成登录:

// 验证验证码并登录
void _verifySmsCode(String smsCode) async {
  try {
    PhoneAuthCredential credential = PhoneAuthProvider.credential(
      verificationId: _verificationId!,
      smsCode: smsCode,
    );
    // 完成登录
    UserCredential userCredential = await _auth.signInWithCredential(credential);
    User? user = userCredential.user;
    if (user != null) {
      print('登录成功!用户ID:${user.uid}');
      // 登录成功后的操作,比如跳转主页、保存用户信息等
    }
  } on FirebaseAuthException catch (e) {
    print('验证码验证失败:${e.message}');
  }
}

4. 监听用户登录状态(可选)

如果需要实时监听用户的登录/退出状态,可以添加一个监听:

StreamSubscription<User?>? _authStateListener;

@override
void initState() {
  super.initState();
  // 监听用户状态变化
  _authStateListener = _auth.authStateChanges().listen((User? user) {
    if (user == null) {
      print('用户已退出登录');
    } else {
      print('当前登录用户ID:${user.uid}');
    }
  });
}

@override
void dispose() {
  // 页面销毁时取消监听
  _authStateListener?.cancel();
  super.dispose();
}

三、踩坑提醒

  • 手机号格式一定要正确:必须包含国家代码,比如中国手机号是+8613xxxxxxxxx,不能只写13xxxxxxxxx
  • 安卓端必须配置SHA-1指纹:在Firebase控制台的项目设置里添加,不然会出现验证码发送失败的情况
  • 测试可以用Firebase提供的测试号码:在控制台的手机号码认证设置里添加测试手机号和对应的验证码,避免频繁发送真实短信
  • 如果遇到配额不足的问题:可以在Firebase控制台查看Authentication的配额限制,或者升级对应的套餐

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:11:55