Flutter Firebase Phone Authentication Example

Flutter Firebase Phone authentication is a method that’s provided by Firebase to easily authenticate user using their phone number.

Phone number verification is a very convenient way to authenticate user by sending OTP to given phone number.

In this tutorial, we’re going to learn how to use Firebase Phone Authentication with Flutter step by step. You can download the startup code from here.

Table of Contents

1 Create Firebase Project

First of all, we need to create a new Firebase project and set it up on required platforms.

2 Add SHA-1 and SHA-256 keys to Firebase Project

To get these keys, you need to navigate to the Android directory from your project and apply the following steps.

  •  From your project terminal, enter the following command
    cd android
  • Then, enter this command to generate the keys
    gradlew signingreport

    sha key
  • Copy SHA1 and SHA-256, and add them to the Firebase projectsha key

2 Enable Authentication

Now, after creating your Firebase project and setting up the environment, it’s time to enable authentication. From the dashboard, click on Authentication in the left menu panel, go to sign-in methods, then click Phone and enable it. At this point, you can optionally enter a phone number and create a pin code for testing.

Flutter Firebase Phone Authentication

3 enable safety net (phone verification)

The next step is to enable safety net in order to allow your app to send OTP messages. To do so, go to Google Cloud Console and navigate to APIs and services then click Enable APIs and services.

Flutter Firebase Phone Authentication

Then search for Android Device Verification and enable it

Flutter Firebase Phone Authentication

And there you go, you set up your project for phone verification.

4 Set up Dependencies

Now we have to add the required dependency to Flutter project in pubspec.yaml file. Add the following dependency then click pub get

firebase_auth: ^3.3.13
firebase_core: ^1.14.0
fluttertoast: ^8.0.9

5 Initialize Firebase in Flutter project

Next we have to initialize Firebase in our Flutter project to enable Firebase methods. In you main.dart file, add the following lines of code in the main function. Take note that you first have to add the async word after main() identifier.

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

}

6 Implement Code

Go to login_with_phone.dart file and do the following:

  •  Create an instance of Firebase Auth before the build function

     

    FirebaseAuth auth = FirebaseAuth.instance;
  • Create 2 variables. one is a bool variable (otpVisibility) which is going to indicate when to display the verification code text field. The second is verificationID which is going to store the verification code.

     

    bool otpVisibility = false;
    String verificationID = "";
  •  Create verifyPhone function. This function will send an OTP code via sms to the entered number and handle the verification process

     

    void verifyPhone() async {
      await auth.verifyPhoneNumber(
        timeout: const Duration(minutes: 2),
        phoneNumber: phoneController.text,
        verificationCompleted: (PhoneAuthCredential credential) async {
          await auth.signInWithCredential(credential).then((value){
    
            print("You are logged in successfully");
           Navigator.of(context).push(MaterialPageRoute(builder: (context) => Home()));
          });
        },
        verificationFailed: (FirebaseAuthException e) {
          print(e.message);
        },
        codeSent: (String verificationId, int? resendToken) {
          otpVisibility = true;
          verificationID = verificationId;
          setState(() {});
        },
        codeAutoRetrievalTimeout: (String verificationId) {
    
        },
      );
    }
  • Create signIn() function. This will be responsible to sign the user in with the credential (phone number) after entering the OTP.

     

    void signIn() async {
    
      PhoneAuthCredential credential =
      PhoneAuthProvider.credential(verificationId: verificationID, smsCode: otpController.text);
    
      await auth.signInWithCredential(credential).then((value){
        print("You are logged in successfully");
        Fluttertoast.showToast(
            msg: "You are logged in successfully",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0
        );
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => Home()));
      });
    }
  • Call the functions in onPressed method of the verify button. Within the build function, find the ToDo I created in the onPressed method of the Elevated button and add the following code

     

    onPressed: () {
      if(otpVisibility){
        //ToDo: signIn
        signIn();
      }
      else {
        //Todo: verify
        verifyPhone();
      }
    }, 
    
    

     

Test the code

For a better result, I advise you to run the code on a physical phone instead of the emulator. This is because sending the OTP while running the emulator is somewhat confusing and time consuming hence it’s easier if you run it on your physical phone.

Flutter Firebase Phone Authentication
Flutter Firebase Phone Authentication

Conclusion

and there you have it, a complete guide on how to use Firebase phone authentication with Flutter. I hope you enjoyed this tutorial and learnt from it. You can download the final source code from here.

Don’t forget to share this post with your friends who are interested in learning more about Firebase.

Oh hi there!
It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

Let's Do This!

2 thoughts on “Flutter Firebase Phone Authentication Example

  1. I’m nnot that much of a internet reader to be honest but your sites
    really nice, kkeep it up! I’ll go ahead and bookmark your website too
    come back in the future. Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top