Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add sms auto verification in flutter app using firebase_auth (Phone Authentication)?

In my flutter app I am using firebase phone authentication for login purpose. in all way, its working perfectly. By using my current code I have to add sms code explicitly when I receive the code.

How can I make this sms verification automatically in my flutter app?

    Future<void> _sendCodeToPhoneNumber() async {

    final String phone = country + phoneNumberController.text;

    final PhoneVerificationCompleted verificationCompleted =
        (AuthCredential credential) {
      setState(() {
        print(
            'Inside _sendCodeToPhoneNumber: signInWithPhoneNumber auto succeeded: $credential');
      });
    };

    final PhoneVerificationFailed verificationFailed =
        (AuthException authException) {
      setState(() {
        print(
            'Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
      });
    };

    final PhoneCodeSent codeSent =
        (String verificationId, [int forceResendingToken]) async {
      this._verificationId = verificationId;
      print("code sent to " + phone);
      setState(() {
        this.status = AuthStatus.SMS_AUTH;
      });
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
        (String verificationId) {
      this._verificationId = verificationId;

      print("time out");
    };

    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: phone,
        timeout: const Duration(seconds: 1),
        verificationCompleted: verificationCompleted,
        verificationFailed: verificationFailed,
        codeSent: codeSent,
        codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
  }
like image 800
proversion Avatar asked Nov 07 '22 14:11

proversion


1 Answers

In onPhoneVerificationCompleted Write this:

final PhoneVerificationCompleted phoneVerificationCompleted =
    (AuthCredential phoneAuthCredential) async {
  print('Received phone auth credential: $phoneAuthCredential');
  await _auth
      .signInWithCredential(phoneAuthCredential)
      .then((AuthResult result) {
    // signin is successful
    FirebaseUser firebaseUser = result.user;
    // check if user exists already
    getUserDetailsById(firebaseUser.uid).then((value) async {
      if (value == null) {
        // new user sign in
        addDataToFirestore(firebaseUser).then((value) => {
              // new user data added to db
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                builder: (context) => Home(),
              ),
            );
          });
      } else {
        // user already signed in
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => Home(),
          ),
        );
      }
    });
  }).catchError((e) {
    print(e);
  });
};
like image 178
Mhamza007 Avatar answered Nov 15 '22 08:11

Mhamza007