Flutter: OTP is being sent again and again although user is registered in Firebase Auth

Issue

I’m using flutter_auth package to apply Phone Auth. Normally it sends the OTP when a new phone number is registered. But it is sending OTP again and again although the user’s phone number is there in Firebase authentication list

One more thing is it is working fine on few devices, the normal way. Is there any thing wrong with syncing issue? means does it take some time to get sync with firestore or not?

Here’s my code of phone auth What am I doing wrong?

phoneAuth(String phone) async {
      FirebaseAuth _auth = FirebaseAuth.instance;

      _auth.verifyPhoneNumber(
          phoneNumber: phone,
          timeout: Duration(seconds: 60),
          verificationCompleted: (AuthCredential credential) async {
            Navigator.pop(context);
            AuthResult authResult =
                await _auth.signInWithCredential(credential);

            FirebaseUser user = authResult.user;

            if (user != null) {
              Navigator.push(
                  context,
                  new MaterialPageRoute(
                      builder: (context) => AddContacts(
                            user: user,
                          )));
            } else {
              print("ERROR");
            }
          },
          verificationFailed: (AuthException exception) {
            Toast.show('Try Again Later', context,
                backgroundColor: Colors.red,
                duration: 3,
                gravity: Toast.BOTTOM);
          },
          codeSent: (String verification, [int forceResendingToken]) {
            showDialog(
                context: context,
                barrierDismissible: false,
                builder: (context) {
                  return AlertDialog(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                    title: Text('Enter 6-Digit Code'),
                    content: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        TextField(
                          controller: _controllerCode,
                          keyboardType: TextInputType.number,
                          maxLength: 6,
                          decoration: InputDecoration(
                            errorText: validateCode(_controllerCode.text),
                            hintText: 'Enter Code',
                            enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12.0)),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12.0)),
                            errorBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12.0),
                                borderSide: BorderSide(color: Colors.red)),
                            focusedErrorBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12.0),
                                borderSide: BorderSide(color: Colors.red)),
                          ),
                        )
                      ],
                    ),
                    actions: <Widget>[
                      Text(
                        "Wait for Automatic Detection!",
                        style: TextStyle(fontSize: 10, color: Colors.red),
                      ),
                      FlatButton(
                        padding: EdgeInsets.symmetric(horizontal: width * .05),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12)),
                        child: Text("Confirm"),
                        textColor: Colors.white,
                        color: Colors.lightBlue,
                        onPressed: () async {
                          setState(() {
                            _controllerCode.text.isEmpty
                                ? _validateCode = true
                                : _validateCode = false;
                          });
                          final code = _controllerCode.text.trim();
                          AuthCredential credential =
                              PhoneAuthProvider.getCredential(
                                  verificationId: verification, smsCode: code);
                          AuthResult result =
                              await _auth.signInWithCredential(credential);
                          FirebaseUser user = result.user;
                          if (user != null) {
                            Navigator.push(
                                context,
                                new MaterialPageRoute(
                                    builder: (context) => AddContacts(
                                          user: user,
                                        )));
                          } else {
                            Toast.show("ERROR: Code mismatch!", context,
                                backgroundColor: Colors.red,
                                gravity: Toast.TOP);
                          }
                        },
                      )
                    ],
                  );
                });
          },
          codeAutoRetrievalTimeout: null);
    }

Solution

As we discussed the problem on LinkedIn chat privately. We reach to the point of your problem which is – as you said..

OTP should be sent only when the user is log in first time not after that. if I enter my number on another device its send the OTP again

So you was having an issue to understand how the Auth OTP works.

OTP code is sent every time you request it even if you are already registered or logged in on another device.

And you asked then..

Means it will sent the OTP everytime not matter the user is logged in already or new?

The answer is YES, it will. So your codes working fine for now. It’s all about the concepts of how it’s working.

Answered By – Shady Boshra

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *