How to Implement OTP Authentication in Flutter Using Firebase

Nov 8, 2021 | Programming

In today’s world, where security is paramount, implementing OTP (One Time Password) authentication is essential for verifying user identities. This blog will walk you through the steps of creating a Flutter-based OTP authentication component to verify mobile numbers using Firebase Authentication.

Table of Contents

Flutter Support

Version – Flutter 1.17 (stable). We have tested our program in this version; however, it can be used in other versions as well.

Demo

OTP Authentication Demo

Features

  • Select country with flag and country code.
  • Verify mobile number with OTP globally.

Getting Started

To get started with the OTP authentication component, follow these simple steps:

  • Download the sample project and import the widget dart files into your Flutter App.
  • Customize the Widgets UI according to your requirements.

Usage

Integrating the OTP authentication into a sample project involves the following setup process:

Methods

Think of setting up OTP authentication like creating a recipe. You need to follow certain steps and gather the right ingredients:

Step 1: Configure Firebase

In your main method, initial Firebase settings should be established. It’s like preparing your kitchen before cooking:


WidgetsFlutterBinding.ensureInitialized();
Platform.isAndroid
    ? await Firebase.initializeApp(
        options: const FirebaseOptions(
            apiKey: 'xxxxxxxxxxxx-g-famDgC3jx6VV4h-xxxxxx',
            appId: '1:xxxxxxxxxxxx:android:xxxxxxxb7ea052854b0005',
            messagingSenderId: 'xxxxxxxxxxxx',
            projectId: 'flutterxxxxxxxxx-9xxxa'))
    : await Firebase.initializeApp();

Step 2: Setup the Country Picker

Add a country picker widget as you’d choose ingredients for the recipe:


CountryPicker(
    callBackFunction: _callBackFunction
);

Step 3: Configure the OTP Pin Field

You also need to include the following dependencies in your project’s pubspec.yaml file:


otp_pin_field: ^1.2.2
firebase_core: ^2.25.4

Then install the packages by running the command:


flutter pub get

Step 4: Generate the OTP

Generating an OTP is crucial, and you will need the following method:


Future generateOtp(String contact) async {
    final PhoneCodeSent smsOTPSent = (verId, forceResendingToken) {
        verificationId = verId;
    };
    
    try {
        await _auth.verifyPhoneNumber(
            phoneNumber: contact,
            codeAutoRetrievalTimeout: (String verId) {
                verificationId = verId;
            },
            codeSent: smsOTPSent,
            timeout: const Duration(seconds: 60),
            verificationCompleted: (AuthCredential phoneAuthCredential) {},
            verificationFailed: (error) {
                print(error);
            },
        );
    } catch (e) {
        handleError(e as PlatformException);
    }
}

Step 5: Verify the OTP

This method will verify the OTP entered by the user:


Future verifyOtp() async {
    if (smsOTP.isEmpty || smsOTP == '') {
        showAlertDialog(context, 'Please enter the 6 digit OTP');
        return;
    }

    try {
        final AuthCredential credential = PhoneAuthProvider.credential(
            verificationId: verificationId,
            smsCode: smsOTP,
        );

        final UserCredential user = await _auth.signInWithCredential(credential);
        final User? currentUser = _auth.currentUser;
        assert(user.user?.uid == currentUser?.uid);
        Navigator.pushReplacementNamed(context, homeScreen);
    } on PlatformException catch(e) {
        handleError(e);
    } catch (e) {
        print('Error: $e');
    }
}

Step 6: Error Handling

Every great chef knows that errors can happen. Here’s how to handle them:


void handleError(PlatformException error) {
    switch (error.code) {
        case ERROR_INVALID_VERIFICATION_CODE:
            FocusScope.of(context).requestFocus(FocusNode());
            setState(() {
                errorMessage = 'Invalid Code';
            });
            showAlertDialog(context, 'Invalid Code');
            break;
        default:
            showAlertDialog(context, error.message ?? 'Error');
            break;
    }
}

Want to Contribute?

If you’ve created something fabulous or improved this code, feel free to contribute! Fork it, create a new branch for your changes, commit, and submit a pull request.

Need Help Support?

For troubleshooting, consider the following tips:

  • If you encounter issues initializing Firebase, ensure you have completed the Firebase project setup properly.
  • Double-check your dependencies are correctly listed in the pubspec.yaml file.
  • Ensure that the phone number formatting is correct before sending the OTP.
  • If you get an invalid code error, recheck the OTP entered by the user.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Collection of Components

Explore our vast collection of components and free resources for software development across various programming languages. Visit our Free Resources for Software Development.

Changelog

Detailed changes for each release are documented in the CHANGELOG.

License

This project is licensed under the MIT License.

Keywords

Flutter-OTP-Authentication, Firebase-OTP-Authentication, Firebase-Authentication, Firebase, Authentication, OTP-Authentication

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox