Phone Auth in firebase flutter

Kashif Chandio
4 min readJul 21, 2022

--

Flutter App Development is emerging and demanding skill in market where you write code for most of business Apps. In business Apps mostly need user phone or email to be verified so minimum number of spam accounts can be created. Working on flutter since last months I have realized Phone auth is important and necessary to make apps user experience reliable and for security purposes too.

I was doing a project for a client SafeVacu which included Phone Auth in it and google firestore documentation isn’t sufficient for that. I searched a bit and figure out how to deal with it and thought I should write a article for it to facilitate beginners. So I came up with this article.
For phone auth, we can use twillio as well but its costly for your client. You can’t even send a text without being charged. So in favour of client I choosed firebase auth for user phone verification.
Here are some package we used for this.

Firebase core is necessary for flutter to help communicate our app with firebase servers. This actually connects our app to firebase servers. For Phone auth in firebase I used this official package recommended & developed by google.

Both of packages we used are official and developed by firebase google, so we can trust these packages and have good pub points on “pub.dev” store.

Before we move to work on firebase auth/phone auth kindly make sure to initialze firebase core in apps main method before run app like this:

Future<void> main() async {WidgetsFlutterBinding.ensureInitialized();await Firebase.initializeApp();runApp(const MyApp());}

For all of your wondering what ensureInitialized() did? It does nothing but to make sure our app successfully connects with method channels. runApp(MyApp) did it for ourself, if we didn’t include any call before runApp.
Now we will move towards doing phone authentication in our app. Its pretty simple but a tricky task to do, Understand basic concepts and you will be all done without hesitation.

Kindly add your app to your firebase console and don’t forget to include SHA1 and SHA256 in your console project. You can do it manually and with the help of cli using flutterfire( If you are doing in manually, you should include google-services.json file in your android/app and info-plist.json file in iOS project). For getting SHA1 and SHA256 of your project, you can refer to this link.

Prepare a UI for getting User number into a TextFormField.

TextFormField(cursorColor: Colors.teal,controller: controller,keyboardType: TextInputType.phone,style: const TextStyle(color: Colors.black,fontSize: 14,fontWeight: FontWeight.w500),decoration: InputDecoration(//fillColor: Colors.grey.shade300,prefixIcon: CountryCodePicker(searchStyle: const TextStyle(color: Colors.black,fontSize: 14,fontWeight: FontWeight.w500),padding: const EdgeInsets.all(0),//flagWidth: 0.0,onChanged: (value) {phoneNumberCode = value.dialCode!;},initialSelection: 'Canada',showFlag: false,favorite: const ['+49', 'Deutschland'],),focusedBorder: OutlineInputBorder(borderSide: const BorderSide(color: Colors.grey),borderRadius: BorderRadius.circular(10.0),),hintText: 'Phone Number',hintStyle: const TextStyle(color: Colors.black,fontSize: 14,fontWeight: FontWeight.w500),border: OutlineInputBorder(borderSide: const BorderSide(color: Colors.grey),borderRadius: BorderRadius.circular(10.0),),enabledBorder: OutlineInputBorder(borderSide: const BorderSide(color: Colors.grey),borderRadius: BorderRadius.circular(10.0),),errorBorder: OutlineInputBorder(borderSide: const BorderSide(color: Colors.grey),borderRadius: BorderRadius.circular(10.0),),),)

I used CountryCodePicker package for country code selection.

Now its time to send code to user’s selected Number. Here is the code for it:

FirebaseAuth.instance.verifyPhoneNumber(phoneNumber: widget.number,verificationCompleted: (PhoneAuthCredential credential) {},verificationFailed: (FirebaseAuthException e) {ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(‘Message Sending Failed, $e’)));},codeSent: (String verifyId, int? resendToken) {verificationId = verifyId;ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text(‘Message sent’)));},codeAutoRetrievalTimeout: (String verifyId) {},);

It includes event which you can see, codeSent will be the main method we will be utilizing. When a code sent to user, it will trigger this event.
In android systems firebase automatically verify Number if app is on same mobile and verificationCompleted event triggers byself. However you can save the verificationId to check if number is verified or not. Here I am storing this verificationId into a variable and make a attempt to signin with google to see if user isn’t null. Here is the code for it:

Container(margin: const EdgeInsets.only(top: 10, right: 10, left: 10),width: size.width * 0.8,child: PinCodeTextField(appContext: context,length: 6,pastedTextStyle: TextStyle(color: Colors.green.shade600,fontWeight: FontWeight.bold,),obscureText: false,animationType: AnimationType.fade,pinTheme: PinTheme(shape: PinCodeFieldShape.box,borderRadius: BorderRadius.circular(10),fieldHeight: 50,fieldWidth: 40,inactiveFillColor: Colors.white,inactiveColor: Colors.grey.shade200,selectedColor: Colors.grey,selectedFillColor: Colors.white,activeFillColor: Colors.white,activeColor: Colors.grey),cursorColor: Colors.teal,animationDuration: const Duration(milliseconds: 300),enableActiveFill: true,controller: pinController,keyboardType: TextInputType.number,boxShadows: const [BoxShadow(offset: Offset(0, 1),color: Colors.black12,blurRadius: 10,)],onCompleted: (v) {//do something or move to next screen when code complete},onChanged: (value) {otp = value;}),),const SizedBox(height: 20,),

I am using PinCodeFields package to minimize UI efforts.

Now once user enters the pincode, you can check by attempting signin method see if user is verified.

try {var user = await FirebaseAuth.instance.signInWithCredential(PhoneAuthProvider.credential(verificationId: verificationId,smsCode: otp,));if (user.user != null) {ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('User Verified Successfully')));}else{
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('User Isn't Verified')));
}}

Calling this signInWithCredential from firebaseAuth will return user if its not null(Mean Verified). It will get PhoneAuthProvider object which you can create using otp and verificationId.

Now Its upto you that where you want to go. Hope it will reduce your efforts to get this done.
Happy Coding and please don’t forget to follow and clap this if you found it helpful.

--

--

Kashif Chandio

Flutter Developer and Passionate to Learn new Technologies and Tools