簡體   English   中英

如何通過 flutter 使用 Firebase 電話身份驗證?

[英]How to use Firebase Phone Authentication with flutter?

我正在嘗試使用 flutter 和 firebase 制作應用程序。 我正在使用 FirebaseAuth 進行注冊和登錄。 我將手機號碼和密碼作為輸入,並使用電話號碼創建一個虛擬 email 並使用 firebase auth signInWithEmailPassword 登錄。 我想要做的是第一次用戶注冊,我想將 otp 發送到那個號碼,如果號碼驗證比我想用那個虛擬 email 和密碼注冊。 任何想法如何實現這一目標。 我嘗試了一些東西,但即使 otp 錯誤,用戶也在注冊。

 String email = '';
 String password = '';
 String name = '';
 String contact = '';
 String error = '';
 String smsCode = '';
 String verificationId;
 bool loading = false;

 Future<void> verifyPhone() async {
print('Inside verify phone');
final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
  this.verificationId = verId;
};

final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
  this.verificationId = verId;
  print('Inside code sent');
  smsCodeDialog(context).then((value) {
    print('Signed in');
  });
};

final PhoneVerificationCompleted verifiedSuccess =
    (AuthCredential credential) {
  print('verified');
};

final PhoneVerificationFailed verificationFailed =
    (AuthException exception) {
  print('${exception.message}');
};

if (_formKey.currentState.validate()) {
  await FirebaseAuth.instance.verifyPhoneNumber(
    phoneNumber: '+91 ' + contact,
    timeout: const Duration(seconds: 10),
    verificationCompleted: verifiedSuccess,
    verificationFailed: verificationFailed,
    codeSent: smsCodeSent,
    codeAutoRetrievalTimeout: autoRetrieve,
  );
}
 }

 Future<bool> smsCodeDialog(BuildContext context) {
return showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return new AlertDialog(
        title: Text('Enter SMS Code'),
        content: TextField(
          onChanged: (value) {
            this.smsCode = value;
          },
        ),
        contentPadding: EdgeInsets.all(10),
        actions: <Widget>[
          TextButton(
              onPressed: () async {
                dynamic result =
                    await _auth.register(email, password, name, contact);
                if (result == null) {
                  Navigator.pop(context);
                  setState(() {
                    loading = false;
                    error = "Already registered or Invalid Details.";
                  });
                } else {
                  Navigator.pop(context);
                  Navigator.pushNamedAndRemoveUntil(
                      context, '/', (Route<dynamic> route) => false);
                }
              },
              child: Text('Register',
                  style: GoogleFonts.abhayaLibre(
                      textStyle: TextStyle(
                          fontSize: 24, color: Colors.green[900]))))
        ],
      );
    });
 }

在提交表單時,我正在調用 verifyPhone 方法。

Future<bool> signIn() async {
try {
  final AuthCredential credential = PhoneAuthProvider.getCredential(
    verificationId: verificationId,
    smsCode: smsCode,
  );
  final AuthResult userResult =
      await _auth.signInWithCredential(credential);
  final FirebaseUser currentUser = await _auth.currentUser();

  final document =
      Firestore().collection("users").document(currentUser.uid);
  final documentSnapshot = await document.get();
  if (!documentSnapshot.exists) {
    await document.setData({
      "id": currentUser.uid,
      "number": phoneNumber,
    });
  }
  return true;
} catch (e) {
  return false;
}

}

  onPressed: () async {
                                      if (_smsController.text.isEmpty) {
                                        widget.scaffoldKey.currentState
                                            .showSnackBar(SnackBar(
                                          content: Text(
                                              "Please enter your SMS code"),
                                          duration: Duration(seconds: 2),
                                        ));
                                        return;
                                      }

                                      await _auth
                                          .currentUser()
                                          .then((user) async {
                                        await signIn()
                                            .then((bool isSignedIn) async {
                                          if (isSignedIn) {
                                            Navigator.of(context)
                                                .pushAndRemoveUntil();
                                          } else {
                                            widget.scaffoldKey.currentState
                                                .showSnackBar(SnackBar(
                                              content:
                                                  Text("Incorrect Code"),
                                              duration:
                                                  Duration(seconds: 2),
                                            ));
                                          }
                                        });
                                      });
                                    },

在這里,我可以向您展示一個最小的示例,該示例還使用 firestore 為用戶存儲額外信息,只要按下 SMS 對話框的按鈕,就會觸發 onPressed

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM