![](/img/trans.png)
[英]How to check if phone number is already registered in firebase authentication using flutter
[英]How to implement phone number verification in flutter using firebase? (Not Authentication)
如何使用firebase實現flutter的電話號碼驗證? 我的應用程序需要在某個時間點驗證電話號碼。 不需要通過電話號碼進行身份驗證。 我只需要驗證我的號碼。 我如何實施?
在 Firebase 中,電話號碼驗證也會自動對用戶進行身份驗證。 如果用戶不登錄,則無法使用 Firebase 身份驗證來驗證用戶的電話號碼。
在 firebase 中確實如此,您不能只驗證電話號碼,電話號碼驗證會自動對用戶進行身份驗證,但這沒關系。 您可以將電話號碼鏈接到已通過身份驗證的用戶。 鏈接電話號碼意味着用戶可以使用他們現有的提供商(gmail、Facebook、email 等)登錄,也可以使用他們的電話號碼登錄並使用相同的帳戶密碼。
請參閱示例 flutter 代碼
_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) {},
);
}
在_displayPhoneNumberVerificationDialog(verificationId)
中有一個帶有提交按鈕的對話。 鏈接邏輯將是按鈕的 onTap。
示例 _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
}
},
)
],
);
});
}
手動執行,使用PhoneNumberUtil類和代碼中的手動方法來驗證國家/地區代碼
在這種情況下,該方法檢查號碼的國家/地區代碼,我指定只允許帶有國家/地區代碼“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;
});
}
然后在你的表格中有
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;
},
)),
然后在表單提交檢查表單狀態
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');
}
},
),
注意:從我的工作代碼中復制了片段,我的驗證將與您想要的不同,但您需要的只是邏輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.