Phone Authentication Using Firebase In Flutter

You’ll get to know about how to use phone authentication using firebase in flutter. I’ll show you how to do phone auth in flutter project like whatsapp, viber and imo. If you are not registered then it will redirect to the register screen and if you are a registered user then it will redirect to homepage.

Here we go:

Firebase setup

  1. Create firebase project for your app →click
  2. Register your flutter app in the firebase project you’ve created above.
  3. Add SHA-1 key in the registration process of firebase project.
    (Generate SHA-1 Key → click)
  4. Download googleservice.json file.
  5. Follow the steps mentioned there in the firebase and do accordingly.
  6. Navigate to the Authentication section in the firebase console.
  7. Enable phone provider
  8. Navigate to Firebase Database
  9. Select Production Mode and choose the location and create database.
  10. Go to rules and replace false with true and publish the changes.
Step 5 illustration
Step 7 illustration
Step 10 illustration

Flutter Project

Note: before diving below, be sure you’d done accordingly as in the above steps.

  1. Add googleservice.json file in the android/app folder of your flutter project which you had downloaded in the earlier steps.
  2. Initialize the following packages in the pubspec.yaml.
firebase_auth: any
firebase_core: any
cloud_firestore: any
get: any

3. Navigate to the app/build.gradle file and add the following line in the defaultConfig section.

defaultConfig {
...
multiDexEnabled true
}

4. Create a class for adding phone number to the firebase collection called “PhoneList”

import 'package:cloud_firestore/cloud_firestore.dart';class PhoneList{
static FirebaseFirestore
_firebaseFirestore =FirebaseFirestore.instance;
static Future<DocumentReference> addphoneList(String item){
CollectionReference
_itemReference = _firebaseFirestore.collection("PhoneList");
var data={
'phn':item,
};
print("done");
return _itemReference.add(data);
}
}

5. Create a function that do phone authentication and sends otp to user device.

class AuthCon extends GetxController{
late String smsOTP;
late String verificationId;
String errorMessage = '';
FirebaseAuth _auth=FirebaseAuth.instance;
Future<void> authF(context,int a,{required String phone}) async {
await _auth.verifyPhoneNumber(
phoneNumber: "+977"+phone, // use your own country code
timeout: const Duration(seconds: 60),
verificationCompleted: _verificationCompleted,
verificationFailed: _exceptionF,
codeSent:(String verificationId,int? resendToken)async{
this.verificationId=verificationId;
_otpBox(context,a,phone);
},
codeAutoRetrievalTimeout: (String verificationId) {
this.verificationId=verificationId;
},);
}
_verificationCompleted(PhoneAuthCredential credential)async{
// Navigator.of(context).pop();
UserCredential result =
await _auth.signInWithCredential(credential);
User? user = result.user;
if(user != null){
Get.to(()=> HomePage());
}else{
print("Error");
}
}
_exceptionF (FirebaseAuthException e) {
if (e.code == 'invalid-phone-number') {
print('The provided phone number is not valid.');
}
}
_otpBox(context,int a,String phone)=>showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text('Enter SMS Code'),
content: Container(
height: 85,
child: Column(
children: [
TextField(onChanged:(value){this.smsOTP = value;},),
(errorMessage != '' ?
Text(errorMessage,style: TextStyle(color: Colors.red),)
: Container())
]),),
contentPadding: EdgeInsets.all(10),
actions: <Widget>[
FlatButton(
child: Text('Done'),
onPressed: ()async {
AuthCredential credential = PhoneAuthProvider.credential
(verificationId: verificationId, smsCode: smsOTP);
UserCredential result =
await _auth.signInWithCredential(credential);
User? user = result.user;
if(user != null){
if(a==0) await PhoneList.addphoneList(phone);
Navigator.push(context, MaterialPageRoute(
builder:(context) => HomePage()));
}else{
print("Error");
}
})],);});
}

6. Create a login button function after initializing firestore

FirebaseFirestore _firebaseFirestore =FirebaseFirestore.instance;
...
...
onPressed: ()async {
List<String> abc=[];
await _firebaseFirestore.collection('PhoneList').get().then((value){
value.docChanges.forEach((e) {
abc.add(e.doc['phn'].toString());
});
});
int z=abc.indexOf(_phoneNumberController.text);
z>=0? Get.find<AuthCon>().signUP(context,1,
phone: _phoneNumberController.text,)
:Get.to(()=>RegisterScreen());
},

7. Create a register button function

onPressed: () {
Get.find<AuthCon>().signUP(context,0,
phone: _phoneNumberController.text);
},

Hence now we had covered all the things. So collaborating all in one, I will say:
“I had created a login and and register page. If user entered phone number and when hit a login button it first check whether its in database or not. If it is there, then it will send otp to the user entered mobile and and navigate to homepage after successful login. If user entered phone number is not in the database then it redirect to registration screen and when user hit register button it will add that number to the database and sends otp to the user number and finally navigate to homepage. For checking the value, whether the signup function is calling from register screen or login screen I had used “a” variable.”
You will get the whole code here.

For push notification → click
For Hosting flutter Web Projects to firebase → cllick

For more info buy the book “Make Yourself The Software Developer: Let’s Dive into Flutter & MNCs” buy.

Keep Learning
Keep Coding:):)
Connect me here if you have any queries:
LinkedIN
Github
Thanks

--

--

--

Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Report: On Scalability (Part Two)

Here’s what actually went down at the 2019 Mojaloop Bootcamp.

Fifth Phase — Experience and Learning

Solving recurrence relations — In Simple Language

How I built a Twitter Bot using Python and Selenium?

Twitter Bots using Python

How To Visualize Spark Dataframes In Scala

HACK THE BOX-MANGO

Growth: My Path to Software Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lakshydeep Vikram

Lakshydeep Vikram

Software Developer

More from Medium

Flutter Authentication with Firebase.

Introduction to flutter

FittedBox Widget in Flutter

flutter web & free firbase hosting