How to do Phone Authentication in Flutter using Firebase?

前端 未结 6 1649
刺人心
刺人心 2021-02-02 02:27

I have searched many websites and I didn\'t find a way to implement phone authentication in Flutter using Firebase. Can anyone tell me how to this?

6条回答
  •  野的像风
    2021-02-02 03:02

    Below are the steps:-

    1. Get OTP based on Phone Number:-

      void sendOTP(String phoneNumber, PhoneCodeSent codeSent,
            PhoneVerificationFailed verificationFailed) {
          if (!phoneNumber.contains('+')) phoneNumber = '+91' + phoneNumber;
          _firebaseAuth.verifyPhoneNumber(
              phoneNumber: phoneNumber,
              timeout: Duration(seconds: 30),
              verificationCompleted: null,
              verificationFailed: verificationFailed,
              codeSent: codeSent,
              codeAutoRetrievalTimeout: null);   }
      
    2. Use the codeSent function to retrieve verification_id and pass it to OTP screen

      void codeSent(String verificationId, [int forceResendingToken]) {
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => Otp(
                    phoneNumber: _phoneNumber,
                    verificationId: verificationId,
                  )));
      }
      
    3. Get user based on verification_id and OTP

      Future verifyOTP(String verificationId, String otp) async {
      AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId,
        smsCode: otp,
      );
      AuthResult result;
      try {
        result = await _firebaseAuth.signInWithCredential(credential);
      } catch (e) {
        // throw e;
        return false;
      }
      print(result);
      (await result.user.getIdToken()).claims.forEach((k, v) {
        print('k= $k and v= $v');
      });
      if (result.user.uid != null) return true;
      return false;
      }
      

    For more details watch the below video

    https://youtu.be/e5M3EwJJYS4

提交回复
热议问题