Demo Project to show how to use Phone Authentication in Flutter with Firebase backend

Overview

Firebase Phone Authentication using Firebase

Demo Project to show how to do Phone Authentication in Flutter using Firebase backend.

Screenshots

At First PhoneNo is entered and submitted
At First PhoneNo is entered and submitted
After OTP is entered & submitted App is restarted
After OTP is entered & submitted App is restarted

Motivation

I felt there is no setp-by-step documentation for Firebase Phone Authentication in Flutter. There were couple of implementations on Medium but are out-dated and one article got it but that failed to explain some crucial concepts. AndroidX brought a lot of changes in addition to FlutterFire plugins update. I asked this question on stackoverflow almost 2 years ago, but failed to get step-by-step answer. So I created this demo project.

Setup Firebase with Flutter

You can setup Firebase by following this guide: https://firebase.google.com/docs/flutter/setup

If you encounter errors with MultiDex or AndroidX make sure you follow below steps

// Inside android folder in app level build.gradle file
...
android {
  ...
  defaultConfig {
    ...
    multiDexEnabled true // add this
  }
  ...
}
...
dependencies {
  // implementation 'com.android.support:multidex:1.0.3' // No AndroidX support
  implementation 'com.android.support:multidex:2.0.1' // Add this to support AndroidX
  implementation 'androidx.browser:browser:1.2.0' // To display verification webpage in the user's default browser
  ...
}
...

Steps

  1. Ask for user's phoneNumber
  2. Get OTP from Firebase
  3. SignIn to Firebase

Rules

  • SignIn/Login is done in the same way.
  • The OTP is only used to get AuthCrendential object
  • AuthCredential object is the only thing that is used to signIn the user. It is obtained either from verificationCompleted callback function in verifyPhoneNumber or from the PhoneAuthProvider. (Don't worry if it's confusing, keep reading, you'll get it)

Workflow

  1. User gives the phoneNumber
  2. Firebase sends OTP
  3. SignIn the user
    • If the SIM card with the phoneNumber is not in the device that is currently running the app,
      • We have to first ask the OTP and get AuthCredential object
      • Next we can use that AuthCredential to signIn This method works even if the phoneNumber is in the device
    • Else if user provided SIM phoneNumber is in the device running the app,
      • We can signIn without the OTP.
      • because the verificationCompleted callback from submitPhoneNumber function gives the AuthCredential object which is needed to signIn the user
      • But in the previous case it ain't called because the SIM is not in the phone.

Functions

  • SubmitPhoneNumber
Future<void> _submitPhoneNumber() async {
    /// NOTE: Either append your phone number country code or add in the code itself
    /// Since I'm in India we use "+91 " as prefix `phoneNumber`
    String phoneNumber = "+91 " + _phoneNumberController.text.toString().trim();
    print(phoneNumber);

    /// The below functions are the callbacks, separated so as to make code more redable
    void verificationCompleted(AuthCredential phoneAuthCredential) {
      print('verificationCompleted');
      ...
      this._phoneAuthCredential = phoneAuthCredential;
      print(phoneAuthCredential);
    }

    void verificationFailed(AuthException error) {
      ...
      print(error);
    }

    void codeSent(String verificationId, [int code]) {
      ...
      print('codeSent');
    }

    void codeAutoRetrievalTimeout(String verificationId) {
      ...
      print('codeAutoRetrievalTimeout');
    }

    await FirebaseAuth.instance.verifyPhoneNumber(
      /// Make sure to prefix with your country code
      phoneNumber: phoneNumber,

      /// `seconds` didn't work. The underlying implementation code only reads in `millisenconds`
      timeout: Duration(milliseconds: 10000),

      /// If the SIM (with phoneNumber) is in the current device this function is called.
      /// This function gives `AuthCredential`. Moreover `login` function can be called from this callback
      verificationCompleted: verificationCompleted,

      /// Called when the verification is failed
      verificationFailed: verificationFailed,

      /// This is called after the OTP is sent. Gives a `verificationId` and `code`
      codeSent: codeSent,

      /// After automatic code retrival `tmeout` this function is called
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
    ); // All the callbacks are above
  }
  • SubmitOTP
void _submitOTP() {
    /// get the `smsCode` from the user
    String smsCode = _otpController.text.toString().trim();

    /// when used different phoneNumber other than the current (running) device
    /// we need to use OTP to get `phoneAuthCredential` which is inturn used to signIn/login
    this._phoneAuthCredential = PhoneAuthProvider.getCredential(
        verificationId: this._verificationId, smsCode: smsCode);

    _login();
  }
  • SignIn/LogIn
Future<void> _login() async {
    /// This method is used to login the user
    /// `AuthCredential`(`_phoneAuthCredential`) is needed for the signIn method
    /// After the signIn method from `AuthResult` we can get `FirebaserUser`(`_firebaseUser`)
    try {
      await FirebaseAuth.instance
          .signInWithCredential(this._phoneAuthCredential)
          .then((AuthResult authRes) {
        _firebaseUser = authRes.user;
        print(_firebaseUser.toString());
      });
      ...
    } catch (e) {
      ...
      print(e.toString());
    }
  }
  • Logout
  Future<void> _logout() async {
    /// Method to Logout the `FirebaseUser` (`_firebaseUser`)
    try {
      // signout code
      await FirebaseAuth.instance.signOut();
      _firebaseUser = null;
      ...
    } catch (e) {
      ...
      print(e.toString());
    }
  }

For more details on implementation please refer to the lib/main.dart file.

Contributions

  • Please feel free to contribute to this README (Pull Requests) and this stackoverflow answer
  • If you find this README useful please star the repository
You might also like...

Let's setup Firebase​​ for our Flutter​​ app on Android​, iOS​ and Flutter Web. Setup Firebase to use Firebase products.

Let's setup Firebase​​ for our Flutter​​ app on Android​, iOS​ and Flutter Web.  Setup Firebase to use Firebase products.

Flutter Tutorial - Firebase Setup For Flutter Web Let's setup Firebase for our Flutter app on Android, iOS and Flutter Web. Setup Firebase to use Fire

Apr 27, 2022

A mobile client for the public apis repository, 1400+ free apis to use able to be navigated through your phone :)

A mobile client for the public apis repository, 1400+ free apis to use able to be navigated through your phone :)

Public APIs mobile app Your assistant app that will help you discover and pick the next API for your next development project What it contains, you sa

Dec 25, 2022

E-Commerce App with getx phone Authtentication and many features flutter firebase

ecommerce_app_getx A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you start

Oct 12, 2022

Food-app-flutter - A simple food ordering application with an admin panel coded with flutter and uses firebase as a backend

Food-app-flutter - A simple food ordering application with an admin panel coded with flutter and uses firebase as a backend

shop_ui A new Flutter project. Getting Started This project is a starting point

Oct 5, 2022

Working Instagram Clone (Frontend + Backend) created with Flutter and Firebase

Working Instagram Clone (Frontend + Backend) created with Flutter and Firebase

Instagram_clone Instagram Clone (Both frontend and backend) created with Flutter and Firebase. Show some ❤️ and star the repo to support the project.

Dec 31, 2022

IoTF app is a smart farming app for IoT and AI-powered tomato plant disease detection. It is built with Flutter and uses Firebase as its backend.

Internet of Tomato Farming IoTF app is a smart farming app for IoT and AI-powered tomato plant disease detection. It is built with Flutter and uses Fi

Dec 9, 2022

This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two pages application with user bid in input and count down view.

This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality.  In addition to that, it's a two pages application with user bid in input and count down view.

Nilam This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two

Nov 9, 2022

All four are used to log into a Firebase backend.

All four are used to log into a Firebase backend.

Auth This library package works with four plugins: firebase_auth google_sign_in flutter_facebook_login flutter_twitter All four are used to log into a

Dec 14, 2022
Comments
  • Persistent login

    Persistent login

    Sorry if it's too much of a basic question (i am a newbie on Flutter), but my problem is that once a user goes through the login and enters the app, once the app gets killed and restarted, the user is facing the login again.

    How to avoid this?

    Thanks

    opened by mpor 3
  • Added Browser Dependency

    Added Browser Dependency

    Added browser dependency...my app was crashing everytime i pressed for send otp..Finally, this thing help me out and browser is opening now for captcha verification :) Thanks for your work, this is really helpful for me :)

    opened by sxmeer-ahmed 2
Owner
Kune Mohith
Data Scientist | Developer | Pentester. Computer Science graduate from NIT Andhra Pradesh.
Kune Mohith
it's just phone number authentication and connected to firebase

simplevar A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

vivek kumar 0 Dec 27, 2021
Firebase Authentication using Phone (All Functionalities)

Dyeus Preview Note: Preview doesn't include auto-detection of OTP due to privacy concerns. The mobile number used is a whitelisted number on firebase

Sarvagya Verma 1 Nov 10, 2022
A Note app built with flutter and integrate with Firebase for user authentication and backend database.

Note App Note app (Both frontend and backend) created with Flutter and Firebase. Complete UI Contains Sign in & Sign up Home Screen Setting screen Acc

Hafiz Mounim Naeem 6 Dec 4, 2022
Presentation-Remote-PC - Manage your presentation from your smart phone - Phone Client

Presentation-Remote-PC Manage your presentation from your smart phone - Phone Cl

Hasan Ragab Eltantawy 1 Jan 25, 2022
Connect your flutter app to firebase, use firebase's Authentication. Don't mind my poor UI. 😬

flutter_email_auth A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you start

Syed Muhammad Ahmad 2 May 2, 2022
Learn how to use firebase authentication in flutter

Flutter simple firebase authentication with Flutter Bloc Flutter Version: Stable 2.5.1 Login with Google, Facebook, email & anonymously using Firebase

Yayo Arellano 8 May 4, 2022
Web3-demo-flutter - A demo for the flutter web3 library.

web3_demo_flutter A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you starte

Tommaso Azzalin 0 Oct 7, 2022
Show a draggable floating chat icon button and show messages on screens

Show a draggable floating chat icon button and show messages on screens Features A widget for displaying a chat icon (or custom widget) on top of a ba

CU Apps 4 May 5, 2022
Flutter firebase auth - Simple implementation of Firebase Authentication using Flutter

FlutterFire Authentication Sample A simple implementation of Firebase Authentica

Souvik Biswas 4 Apr 2, 2022
A demo Project Showcasing HowTo use GraphQL to conect as a client to a GraphQL service.

graphql_demoapp A Flutter App to demonstrate how to work with GraphQL Server, connecting through our app as a client. Working with basic queries and m

Igor L Sambo 2 Nov 7, 2021