简体   繁体   中英

How to implement phone number verification in flutter using firebase? (Not Authentication)

how to implement phone number verification in flutter using firebase?. my app need to verify the phone number at a point of time. not needed authentication by phone number. I just need to verify my number. How I implement that?

In Firebase phone number verification automatically also authenticates the user. There is no way to verify a user's phone number with Firebase Authentication without signing the user in.

It's true in firebase you can't just verify a phone number and that a phone number verification automatically authenticates the user but that's okay. You can link a phone number to an already authenticated user. Linking the phone number means that the user can log in with their already existing provider (gmail, Facebook, email, etc) as well as log in with their phone number and use the same password for their account.

See sample flutter code

_verifyPhoneNumber() async {
    await FirebaseAuth.instance.verifyPhoneNumber(
    phoneNumber: '+44 7123 123 456',
    verificationCompleted: (PhoneAuthCredential credential) {
     // For andriod only automatic handling of the SMS code
    },
    verificationFailed: (FirebaseAuthException e) {},
    codeSent: (String verificationId, int? resendToken) {
      // SMS Code sent show a dialogue to enter the code.
     _displayPhoneNumberVerificationDialog(verificationId);
    },
    codeAutoRetrievalTimeout: (String verificationId) {},
  );
}

Inside _displayPhoneNumberVerificationDialog(verificationId) have a dialogue with a submit button. The linking logic will be onTap of the button.

Sample _displayPhoneNumberVerificationDialog

_displayPhoneNumberVerificationDialogSt(String verificationId) {
      FirebaseAuth firebaseAuth = firebase.FirebaseAuth.instance;
      return showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('Enter verification code'),
              content: TextField(
                keyboardType: TextInputType.number,
                textInputAction: TextInputAction.done,
                decoration: InputDecoration(hintText: "phone number"),
                onChanged: (input) {
                  _smsVerificationCode = input;
                },
              ),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('Submit'),
                  onPressed: () async {
                    Navigator.of(context).pop();
                    // Create a PhoneAuthCredential with the code
                    PhoneAuthCredential credential;
                    try {
                      credential = PhoneAuthProvider.credential(
                          verificationId: verificationId,
                          smsCode: _smsVerificationCode);
                    } catch (e) {
                      // Show Error usually wrong _smsVerfication code entered
                      return;
                    }
                    User currentUser = await firebaseAuth.getCurrentUser();
                    try {
                      // This try catch helps if you want to update an existing verified phone number and you want to verify the new one.
                      // We unlink the old phone number so a new one can be linked
                      // This is not relevant if you're just going to verify and link a phone number without updating it later.
                      currentUser = await currentUser.unlink("phone");
                    } catch (e) {
                      print(e);
                      currentUser = await firebaseAuth.getCurrentUser();
                    }
                    try {
                      currentUser.linkWithCredential(credential).then((value) {
                        // Verfied now perform something or exit.
                      }).catchError((e) {
                        // An error occured while linking
                      });
                    } catch (e) {
                      // General error
                    }
                  },
                )
              ],
            );
          });
    }

Helpful doc: https://firebase.flutter.dev/docs/auth/phone/

do it manually , using PhoneNumberUtil class and a manual method in code to verify on the country codes

The method checks for the country codes of the number in this case i specify only allow Kenyan Numbers with the country code 'KE'

 _checkPhoneNumber() async {
var s = phoneTextFieldController.text;
bool isValid;
if (s.length == 0) {
  isValid = true;
  setState(() {
    _isPhoneNumber = isValid;
  });
  return;
}
 //check if the number starts with '0' , or '07' or '254'
if (s.length < 10) {
  isValid = s.length == 1 && s[0] == '0' ||
      s.length > 1 && s[0] + s[1] == '07' ||
      s.length > 1 && s[0] + s[1] + s[2] == '254' ||
      s.length > 1 && s[0] + s[1] + s[2] + s[3] == '+254';
  setState(() {
    _isPhoneNumber = isValid;
  });

  return;
}

isValid =
    await PhoneNumberUtil.isValidPhoneNumber(phoneNumber: s, isoCode: 'KE');
String normalizedNumber = await PhoneNumberUtil.normalizePhoneNumber(
    phoneNumber: s, isoCode: 'KE');
RegionInfo regionInfo =
    await PhoneNumberUtil.getRegionInfo(phoneNumber: s, isoCode: 'KE');

setState(() {
  _isPhoneNumber = isValid;
});
}

Then in your form have

child: TextFormField(
                          onChanged: (text) {
                            _checkPhoneNumber();
                          },
                          controller: phoneTextFieldController,
                          keyboardType: TextInputType.phone,

                          validator: (val) {
                            if (val == '') {
                              return 'Phone Number is required';
                            }
                            if (!_isPhoneNumber) {
                              return 'Phone Number format error';
                            }
                          },
                          decoration: InputDecoration(
                              hintText: "2547xx xxx xxx - Phone",
                              border: InputBorder.none,
                              icon: const Icon(
                                Icons.phone,
                              ),
                              labelText: 'Phone',
                              prefixText: '     ',
                              suffixStyle:
                                  const TextStyle(color: Colors.green)),
                          onSaved: (value) {
                            phoneNumberForm = value;
                          },
                        )),

Then on form submit check the form state

 buttonCustom(
                  color: Color(0xFF4458be),
                  heigth: 50.0,
                  txt: contactIdParam!=null ?"Submit Edit":"Submit",
                  ontap: () {
                    final _form = form.currentState;
                    if (_form.validate()) {
                      if(contactIdParam!=null){
                         _editContactRequest();
                      }else{
                        _addContactRequest();

                      }

                    } else {
                      print('form is invalid');
                    }
                  },
                ),

Nb: have copied snippets form my working code my validation will differ from what you want but what you need is just the logic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM