The Sms Code Has Expired. Please Re-send the Verification Code to Try Again.
FirebasePhoneAuthHandler For Palpitate #
- An easy-to-use firebase phone authentication bundle to easily send and verify OTP'southward with auto-fetch OTP back up via SMS.
- Supports OTP on web out of the box.
Step 1: Before you lot tin add together Firebase to your app, you need to create a Firebase project to connect to your application. Visit Understand Firebase Projects
to acquire more virtually Firebase projects.
Footstep 2: To use Firebase in your app, you need to register your app with your Firebase project. Registering your app is often chosen "adding" your app to your projection.
Also, annals a web app if using on the web. Follow on the screen instructions to initialize the projection.
Add the latest version 'firebase-auth' CDN from hither. (Tested on version 8.6.1)
Step 3: Add a Firebase configuration file and the SDK'due south. (google-services)
Step 4: When the basic setup is done, open up the console and then the project and head over to Authentication
from the left drawer carte.
Footstep 5: Click on Sign-in method
next to the Users
tab and enable Telephone
.
Step 6: Follow the boosted configuration steps for the platforms to avoid any errors.
Stride 7: IMPORTANT: Practice not forget to enable the Android Device Verification
service from Google Deject Platform. (make certain the right projection is selected).
Step 8: Lastly, add firebase_core
as a dependency in your pubspec.yaml file. and call Firebase.initializeApp()
in the principal
method every bit shown:
void chief() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(_MainApp()); }
To employ this plugin, add firebase_phone_auth_handler
every bit a dependency in your pubspec.yaml file.
dependencies: flutter: sdk: flutter firebase_phone_auth_handler:
Outset and foremost, import the widget.
import 'package:firebase_phone_auth_handler/firebase_phone_auth_handler.sprint';
Wrap the MaterialApp
with FirebasePhoneAuthProvider
to enable your application to back up phone authentication similar shown.
form _MainApp extends StatelessWidget { @override Widget build(BuildContext context) { render FirebasePhoneAuthProvider( kid: MaterialApp( debugShowCheckedModeBanner: false, home: HomeScreen(), ), ); } }
You can now add a FirebasePhoneAuthHandler
widget to your widget tree and laissez passer all the required parameters to go started.
FirebasePhoneAuthHandler( phoneNumber: "+919876543210", builder: (context, controller) { render SizedBox.shrink(); }, ),
The telephone number is the number to which the OTP will be sent which should be formatted in the post-obit mode:
+919876543210 - where +91 is the country code and 9876543210 is the telephone number.
The widget returned from the builder
is rendered on the screen. The architect exposes a controller
which contains various variables and methods.
Callbacks such every bit onLoginSuccess
or onLoginFailed
tin be passed to the widget.
onLoginSuccess
is called whenever the otp was sent to the mobile successfully and was either auto verified or verified manually by calling verifyOTP
function in the controller. The callback exposes UserCredential
object which can be used to find user UID and other stuff. The boolean provided is whether the OTP was auto verified or verified manually be calling verifyOTP
. Truthful if auto verified and fake is verified manually.
onLoginFailed
is chosen if an error occurs while sending OTP or verifying the OTP or any internal error occurs, callback is triggered exposing FirebaseAuthException
which can be used to handle the error.
FirebasePhoneAuthHandler( phoneNumber: "+919876543210", architect: (context, controller) { return SizedBox.shrink(); }, onLoginSuccess: (userCredential, autoVerified) { debugPrint("autoVerified: $autoVerified"); debugPrint("Login success UID: ${userCredential.user?.uid}"); }, onLoginFailed: (authException) { debugPrint("An error occurred: ${authException.message}"); }, ),
To logout the current user(if whatever), simply call
look FirebasePhoneAuthHandler.signOut(context);
controller.signOut()
tin can also exist used to logout the electric current user if the functionality is needed in the aforementioned screen as the widget itself (where controller
is the variable passed in the callback from the builder method in the widget).
By default, the reCAPTCHA widget is a fully managed menstruum which provides security to your spider web application. The widget will return as an invisible widget when the sign-in flow is triggered. An "invisible" widget will announced as a full-page modal on-top of your application like demonstrated below.
Although, a RecaptchaVerifier
instance can be passed which can exist used to manage the widget.
Utilise the function recaptchaVerifierForWebProvider
in FirebasePhoneAuthHandler
which gives a boolean to check whether the electric current platform is Web or not.
Note
: Practice not pass a RecaptchaVerifier
instance if the platform is not web, else an mistake occurs.
Example:
recaptchaVerifierForWebProvider: (isWeb) { if (isWeb) return RecaptchaVerifier(); },
It is nevertheless possible to display an inline widget which the user has to explicitly press to verify themselves.
To add an inline widget, specify a DOM element ID to the container argument of the RecaptchaVerifier
instance. The element must exist and be empty otherwise an error will be thrown. If no container statement is provided, the widget volition be rendered as "invisible".
RecaptchaVerifier( container: 'recaptcha', size: RecaptchaVerifierSize.compact, theme: RecaptchaVerifierTheme.dark, onSuccess: () => print('reCAPTCHA Completed!'), onError: (FirebaseAuthException error) => print(fault), onExpired: () => print('reCAPTCHA Expired!'), ),
If the reCAPTCHA badge does not disappear automatically afterward authentication is washed, try adding the following code in onLoginSuccess
so that information technology disappears when the login process is done.
Firstly import querySelector
from dart:html
.
import 'dart:html' show querySelector;
Then add this in onLoginSuccess
callback.
terminal captcha = querySelector('#__ff-recaptcha-container'); if (captcha != nil) captcha.subconscious = true;
If you want to completely disable the reCAPTCHA badge (typically appears on the bottom right), add together this CSS fashion in the web/index.html
outside whatsoever other tag.
<way> .grecaptcha-badge { visibility: hidden; } </style>
How I prefer using it commonly
I usually have a telephone number input field, which handles telephone number input. Then pass the phone number to the VerifyPhoneNumberScreen
widget from the example app.
// probably some ui or dialog to become the phone number final phoneNumber = _getPhoneNumber(); // then telephone call void _verifyPhoneNumber() async { Navigator.push( context, MaterialPageRoute( architect: (_) => VerifyPhoneNumberScreen(phoneNumber: phoneNumber), ), ); } /// route to home screen or somewhere in the onLoginSuccess callback for [VerifyPhoneNumberScreen]
Sample Usage
import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_phone_auth_handler/firebase_phone_auth_handler.dart'; import 'packet:flutter/material.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(_MainApp()); } class _MainApp extends StatelessWidget { @override Widget build(BuildContext context) { return FirebasePhoneAuthProvider( child: MaterialApp( debugShowCheckedModeBanner: false, home: VerifyPhoneNumberScreen(phoneNumber: "+919876543210"), ), ); } } // ignore: must_be_immutable course VerifyPhoneNumberScreen extends StatelessWidget { terminal String phoneNumber; String? _enteredOTP; VerifyPhoneNumberScreen({ Key? fundamental, required this.phoneNumber, }) : super(key: fundamental); void _showSnackBar(BuildContext context, String text) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(text)), ); } @override Widget build(BuildContext context) { return SafeArea( child: FirebasePhoneAuthHandler( phoneNumber: phoneNumber, timeOutDuration: const Duration(seconds: sixty), onLoginSuccess: (userCredential, autoVerified) async { _showSnackBar( context, 'Telephone number verified successfully!', ); debugPrint( autoVerified ? "OTP was fetched automatically" : "OTP was verified manually", ); debugPrint("Login Success UID: ${userCredential.user?.uid}"); }, onLoginFailed: (authException) { _showSnackBar( context, 'Something went wrong (${authException.message})', ); debugPrint(authException.bulletin); // handle mistake farther if needed }, architect: (context, controller) { render Scaffold( appBar: AppBar( title: const Text("Verify Phone Number"), actions: [ if (controller.codeSent) TextButton( kid: Text( controller.timerIsActive ? "${controller.timerCount.inSeconds}s" : "RESEND", style: const TextStyle( color: Colors.blue, fontSize: 18, ), ), onPressed: controller.timerIsActive ? cypher : () async => await controller.sendOTP(), ), const SizedBox(width: 5), ], ), body: controller.codeSent ? ListView( padding: const EdgeInsets.all(20), children: [ Text( "We've sent an SMS with a verification code to $phoneNumber", way: const TextStyle( fontSize: 25, ), ), const SizedBox(superlative: 10), const Divider(), AnimatedContainer( elapsing: const Duration(seconds: 1), height: controller.timerIsActive ? aught : 0, child: Column( children: const [ CircularProgressIndicator.adaptive(), SizedBox(height: l), Text( "Listening for OTP", textAlign: TextAlign.eye, style: TextStyle( fontSize: 25, fontWeight: FontWeight.w600, ), ), Divider(), Text("OR", textAlign: TextAlign.eye), Divider(), ], ), ), const Text( "Enter OTP", style: TextStyle( fontSize: 20, fontWeight: FontWeight.w600, ), ), TextField( maxLength: six, keyboardType: TextInputType.number, onChanged: (String 5) async { _enteredOTP = v; if (_enteredOTP?.length == 6) { concluding isValidOTP = await controller.verifyOTP( otp: _enteredOTP!, ); // Incorrect OTP if (!isValidOTP) { _showSnackBar( context, "Delight enter the correct OTP sent to $phoneNumber", ); } } }, ), ], ) : Column( mainAxisAlignment: MainAxisAlignment.heart, crossAxisAlignment: CrossAxisAlignment.center, children: const [ CircularProgressIndicator.adaptive(), SizedBox(height: 50), Center( child: Text( "Sending OTP", style: TextStyle(fontSize: 25), ), ), ], ), ); }, ), ); } }
See the instance
directory for a complete sample app.
Created & Maintained Past Rithik Bhandari
#
- GitHub: @rithik-dev
- LinkedIn: @rithik-bhandari
Source: https://pub.dev/packages/firebase_phone_auth_handler
0 Response to "The Sms Code Has Expired. Please Re-send the Verification Code to Try Again."
Post a Comment