Firebase phone auth with flutter(latest update)

Mohammad Fayaz
4 min readMay 29, 2019

Firebase is Google’s mobile platform that helps you quickly develop high-quality apps and grow your business.

Firebase provide you bunch of options that you can use them for your web app and mobile, let’s see how we can setup and use firebase phone authentication feature for flutter apps.

  • Connect your app to firebase
  • Setup phone auth
  • Import the firebase_auth plugin
  • Setup authentication feature in your app
  • Migrate your flutter app to Android X

Connecting your app to firebase

Head to https://console.firebase.google.com/, and signin with your Google account, then create a new Project as follows

Firebase console website
Creating a new project
Once you are done creating the project, your project’s dashboard will be shown

Add an Android app to your Firebase project

Enter the necessary details, and register your app. You can find the package name inside the build.gradle file of your android app module.

Download the google-services.json file and place it inside your app folder of your android project.

Add the classpath and dependencies declarations and you are done.

Enable phone auth method, in the authentication section.

Now, let’s head on to the flutter code

Import the firebase_auth package in your project’s pubspec.yaml file, you can find the package at https://pub.dev/packages/firebase_auth. Add it and run flutter packages get command.

Create a dart file for firebase phone auth, that includes a field for entering the phone number, a field for getting the verification code.

var firebaseAuth = await FirebaseAuth.instance;firebaseAuth.verifyPhoneNumber(
phoneNumber: phone,
timeout: Duration(seconds: 60),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);

Write the methods that accomplish the task.

final PhoneCodeSent codeSent =
(String verificationId, [int forceResendingToken]) async {
this.actualCode = verificationId;
setState(() {
print('Code sent to $phone');
status = "\nEnter the code sent to " + phone;
});
};
final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verificationId) {
this.actualCode = verificationId;
setState(() {
status = "\nAuto retrieval time out";
});
};
final PhoneVerificationFailed verificationFailed =
(AuthException authException) {
setState(() {
status = '${authException.message}';

print("Error message: " + status);
if (authException.message.contains('not authorized'))
status = 'Something has gone wrong, please try later';
else if (authException.message.contains('Network'))
status = 'Please check your internet connection and try again';
else
status
= 'Something has gone wrong, please try later';
});
};

The verificationCompleted, is executed automatically when the system detects the verification code, use the onAuthenticationSuccessful() method to perform actions when authentication is obtained.

final PhoneVerificationCompleted verificationCompleted =
(AuthCredential auth) {
setState(() {
status = 'Auto retrieving verification code';
});
//_authCredential = auth;

firebaseAuth
.signInWithCredential(_authCredential)
.then((AuthResult value) {
if (value.user != null) {
setState(() {
status = 'Authentication successful';
});
onAuthenticationSuccessful();
} else {
setState(() {
status = 'Invalid code/invalid authentication';
});
}
}).catchError((error) {
setState(() {
status = 'Something has gone wrong, please try later';
});
});
};

If the verification code auto-retrieval doesn’t succeed, then ask the user to enter the otp manually and execute the following code. For this you need to create an instance of AuthCredential, this takes verification id and smsCode the user enters.

void _signInWithPhoneNumber(String smsCode) async {
_authCredential = await PhoneAuthProvider.getCredential(
verificationId: actualCode, smsCode: smsCode);
firebaseAuth.signInWithCredential(_authCredential).catchError((error) {
setState(() {
status = 'Something has gone wrong, please try later';
});
}).then((FirebaseUser user) async {
setState(() {
status = 'Authentication successful';
});
onAuthenticationSuccessful();
});
}

That’s it you are done.

For more info, checkout this repo https://github.com/fayaz07/flutter_firebase

The above repo includes complete firebase authentication with phone(others will be updated soon), below are the screens you can expect as output

--

--