I have implemented the Phone Authentication in FLutter and its working. I just need to add a functionality.
Check whether the user has entered the correct otp which is received on the entered phone number or not If the entered otp is incorrect error message should be displayed.
some code snippet:
AuthService.dart
class AuthService{
handleAuth(){
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (BuildContext context, snapshot){
if(snapshot.hasData){
return LoginSuccessScreen();
}
else{
return SignInScreen();
}
}
);
}
signOut(){
FirebaseAuth.instance.signOut();
}
signIn(AuthCredential authCreds){
FirebaseAuth.instance.signInWithCredential(authCreds);
}
signInWithOtp(context,smsCode,verId){
AuthCredential authCreds = PhoneAuthProvider.getCredential(
verificationId: verId,
smsCode: smsCode
);
Navigator.pushReplacement(context,
MaterialPageRoute(
builder: (context) => LoginSuccessScreen()
)
);
signIn(authCreds);
}
SignIn.dart
Future<void> verifyPhone(phoneNo) async {
final PhoneVerificationCompleted verified = (AuthCredential authResult){
print('sms1');
AuthService().signIn(authResult);
};
final PhoneVerificationFailed verificationFailed = (AuthException authException){
print('${authException.message}');
verificationFailedErrorExist = true;
setState(() {
});
};
final PhoneCodeSent smsSent = (String verId, [int forceResend]){
this.verificationId = verId;
print('sms');
Navigator.pushReplacement(context,
MaterialPageRoute(
builder: (context) => OtpScreen(verificationId)
)
);
setState(() {
});
};
final PhoneCodeAutoRetrievalTimeout autoTimeOut = (String verId){
this.verificationId = verId;
};
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNo,
timeout: const Duration(seconds: 30),
verificationCompleted: verified,
verificationFailed: verificationFailed,
codeSent: smsSent,
codeAutoRetrievalTimeout: autoTimeOut
);
}
Otp.dart
Widget OtpForm() {
return Form(
child: Column(
children: [
SizedBox(height: SizeConfig.screenHeight * 0.15),
PinCodeTextField(
appContext: context,
length: 6,
onChanged: (value) {
otp = value;
},
keyboardType: TextInputType.number,
errorAnimationController: errorController,
pinTheme: PinTheme(
shape: PinCodeFieldShape.underline,
inactiveColor: Colors.black38,
activeColor: ErrorCode,
),
),
SizedBox(height: SizeConfig.screenHeight * 0.15),
DefaultButton(
text: "Verify OTP",
press: () {
AuthService().signInWithOtp(context,otp, widget.verId);
if (otp.length !=6 ) {
errorController.add(ErrorAnimationType.shake);
ErrorCode = Colors.red;
setState(() {
});
print('nohellp');
}
},
)
],
),
);
}