firebase - 如何使用 Firebase 在 Flutter 中进行电话身份验证?

标签 firebase flutter

我搜索了很多网站,但没有找到使用 Firebase 在 Flutter 中实现电话身份验证的方法。谁能告诉我怎么做?

最佳答案

有据可查的工作演示项目here

下面是详细过程

步骤

  1. 询问用户的电话号码
  2. 从 Firebase 获取 OTP
  3. 登录 Firebase

规则

  • 登录/登录方式相同。
  • OTP 仅用于获取 AuthCrendential 对象
  • AuthCredential 对象是唯一用于登录用户的东西。 它可以从 verifyPhoneNumber 中的 verificationCompleted 回调函数或 PhoneAuthProvider 中获得。

(不要担心,如果它令人困惑,继续阅读,你会明白的)

工作流程

  1. 用户提供 phoneNumber
  2. Firebase 发送 OTP
  3. 登录用户
    • 如果带有 phoneNumber 的 SIM 卡不在当前运行该应用的设备中,
      • 我们必须先询问 OTP 并获取 AuthCredential 对象
      • 接下来我们可以使用那个 AuthCredential 来登录 即使 phoneNumber 在设备中,此方法也有效
    • 否则,如果用户提供的 SIM 电话号码在运行该应用的设备中,
      • 我们可以在没有 OTP 的情况下登录。
      • 因为来自 submitPhoneNumber 函数的 verificationCompleted 回调提供了登录用户所需的 AuthCredential 对象
      • 但在前一种情况下,它没有被调用,因为 SIM 卡不在手机中。

功能

  • 提交电话号码
Future<void> _submitPhoneNumber() async {
    /// NOTE: Either append your phone number country code or add in the code itself
    /// Since I'm in India we use "+91 " as prefix `phoneNumber`
    String phoneNumber = "+91 " + _phoneNumberController.text.toString().trim();
    print(phoneNumber);

    /// The below functions are the callbacks, separated so as to make code more readable
    void verificationCompleted(AuthCredential phoneAuthCredential) {
      print('verificationCompleted');
      ...
      this._phoneAuthCredential = phoneAuthCredential;
      print(phoneAuthCredential);
    }

    void verificationFailed(AuthException error) {
      ...
      print(error);
    }

    void codeSent(String verificationId, [int code]) {
      ...
      print('codeSent');
    }

    void codeAutoRetrievalTimeout(String verificationId) {
      ...
      print('codeAutoRetrievalTimeout');
    }

    await FirebaseAuth.instance.verifyPhoneNumber(
      /// Make sure to prefix with your country code
      phoneNumber: phoneNumber,

      /// `seconds` didn't work. The underlying implementation code only reads in `milliseconds`
      timeout: Duration(milliseconds: 10000),

      /// If the SIM (with phoneNumber) is in the current device this function is called.
      /// This function gives `AuthCredential`. Moreover `login` function can be called from this callback
      verificationCompleted: verificationCompleted,

      /// Called when the verification is failed
      verificationFailed: verificationFailed,

      /// This is called after the OTP is sent. Gives a `verificationId` and `code`
      codeSent: codeSent,

      /// After automatic code retrival `tmeout` this function is called
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
    ); // All the callbacks are above
  }
  • 提交OTP
void _submitOTP() {
    /// get the `smsCode` from the user
    String smsCode = _otpController.text.toString().trim();

    /// when used different phoneNumber other than the current (running) device
    /// we need to use OTP to get `phoneAuthCredential` which is inturn used to signIn/login
    this._phoneAuthCredential = PhoneAuthProvider.getCredential(
        verificationId: this._verificationId, smsCode: smsCode);

    _login();
  }
  • 登录/登录
Future<void> _login() async {
    /// This method is used to login the user
    /// `AuthCredential`(`_phoneAuthCredential`) is needed for the signIn method
    /// After the signIn method from `AuthResult` we can get `FirebaserUser`(`_firebaseUser`)
    try {
      await FirebaseAuth.instance
          .signInWithCredential(this._phoneAuthCredential)
          .then((AuthResult authRes) {
        _firebaseUser = authRes.user;
        print(_firebaseUser.toString());
      });
      ...
    } catch (e) {
      ...
      print(e.toString());
    }
  }
  • 退出
  Future<void> _logout() async {
    /// Method to Logout the `FirebaseUser` (`_firebaseUser`)
    try {
      // signout code
      await FirebaseAuth.instance.signOut();
      _firebaseUser = null;
      ...
    } catch (e) {
      ...
      print(e.toString());
    }
  }

更多实现细节请引用lib/main.dart文件here .

如果您发现问题,欢迎对此答案和 repo README 进行编辑。

关于firebase - 如何使用 Firebase 在 Flutter 中进行电话身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181000/

相关文章:

flutter - Flutter删除showModalBottomSheet的顶部边框

android - 如何确定 Firebase 用户是否使用 facebook 身份验证登录

firebase - 在 Firebase 中,如何确定用户是否具有节点的写访问权限?

firebase - Cloud Functions for Firebase 未设置 Access-Control-Allow-Origin

flutter - 为什么此警报对话框无法正常工作

flutter - 为移动和桌面构建 Flutter 应用程序

java - 如何更改 .push() 在 Android 上的 Firebase 实时数据库中添加数据的索引

xcode - "No such module ' Firebase '"将 Firebase 添加到库中时

flutter - 如何在GetPage flutter中使用自定义Transition

flutter - 如何在 flutter 中获取剪辑的 Container() 的边框