OTP Authentication In Flutter Using Firebase (2022)

Table of Contents
Introduction Conclusion Videos

Introduction

Google Firebase provides phone authentication using SMS. The basic plan of Firebase includes 10k of free SMSes for a month. We will learn Firebase Phone Authentication in Flutter in this article. We will start from Firebase and will programmatically set up the actual integration in Flutter. So, let’s start!

What we will achieve.

OTP Authentication In Flutter Using Firebase (1)

Step 1

The first and most basic step is to create a new application in Flutter. If you are a beginner in Flutter, then you can check my blogCreate your first app in Flutter. I have created an app named “flutter_otp_auth”.

Step 2

Now, you need to set up a project in Google Firebase. Follow the below steps for that. Please follow the steps very carefully.

  • Gohereand add a new project. I will share the screenshot of how it looks so you will get a better idea.
  • Click on "Add Project" to add the new project in Google Firebase. Then, you will find the below form.

    OTP Authentication In Flutter Using Firebase (2)

    OTP Authentication In Flutter Using Firebase (3)

    Video: Flutter - Firebase Mobile phone Authentication| Firebase otp | Tutorial

  • Give a project name and accept the terms and conditions and click on "Create Project". It will take some time to create a new project and redirect you to project the Overview page.
  • Now, you need to add an Android app in this project. You can add a new Android project from clicking on the Android icon. You can also add an iOS project if you want to create an iOS application for the same.

    OTP Authentication In Flutter Using Firebase (4)

  • In Project Overview add an Android app and for that, click on the Android icon. It will open the new form. Please check the below screenshot.

    OTP Authentication In Flutter Using Firebase (5)

  • You will find the Android package name in the AndroidManifest.xml file in Android => App => main folder of your project.
  • App nickname is optional
  • For SHA-1 generation, gohere.
  • In step 2, download google-service.json and put in Android => App folder of your project
  • In step 3, you can see that you need to configure some dependencies.

Project-level build.gradle (<project>/build.gradle): means the build.gradle file should be put in the Android folder directly.

  1. buildscript{
  2. dependencies{
  3. classpath'com.google.gms:google-services:4.2.0'
  4. }
  5. }

App-level build.gradle (<project>/<app-module>/build.gradle): means build.gradle file in Android = > App folder

Note

Video: Flutter - Firebase Mobile Phone Verification | Firebase Auth (2021)

We do not need to add the implementation 'com.google.firebase:firebase-core:16.0.9' in dependencies,

  • In Step 4, it will try to verify your app. For that, you need to run your app once or you can skip this step.
  • Hurray!!! Your Android app has been created.

Step 3

Now, you need to enable the Phone Sign-In method in Firebase. For that, you need to go to the Authentication tab and then, the Sign-in method tab. From there, enable the Phone Sign-in method. Please check the screenshot.

OTP Authentication In Flutter Using Firebase (6)

You are all done with Firebase set up. Congratulations!

Step 4

Get back to the project and open the pubspec.yaml file in the root of the project. Pubspec.yaml is used to define all the dependencies and assets of the project.

    • Add the below dependencies and save the file.

      firebase_auth:

    • Please check the below screenshot. You will get more idea where to add the dependency.

      OTP Authentication In Flutter Using Firebase (7)

      Video: Flutter Phone Authentication | Implementing Phone Auth Using Flutter & Firebase + Source Code

    • Run Flutter packages get in terminal OR If you are using Visual Studio Code then after saving file it will automatically run the Flutter packages get command.
    • Now, we are done with all dependency setup at project side as well…. :)

    Step 5

    Now, we need to programmatically handle OTP Login in Google Firebase. For that, we create 2 pages - main.dart(default) and homepage.dart. I have attached a link of Git repo at the bottom of the article. You can take reference from there. Here, I will just import methods for sending and verifying the OTP. Below is the source code for the dartfile.

    1. import'package:flutter/material.dart';
    2. import'package:firebase_auth/firebase_auth.dart';
    3. import'package:flutter/services.dart';
    4. import'homepage.dart';
    5. voidmain()=>runApp(MyApp());
    6. classMyAppextendsStatelessWidget{
    7. @override
    8. Widgetbuild(BuildContextcontext){
    9. returnMaterialApp(
    10. title:'PhoneAuthentication',
    11. routes:<String,WidgetBuilder>{
    12. '/homepage':(BuildContextcontext)=>MyHome(),
    13. '/loginpage':(BuildContextcontext)=>MyApp(),
    14. },
    15. theme:ThemeData(
    16. primarySwatch:Colors.blue,
    17. ),
    18. home:MyAppPage(title:'PhoneAuthentication'),
    19. );
    20. }
    21. }
    22. classMyAppPageextendsStatefulWidget{
    23. MyAppPage({Keykey,this.title}):super(key:key);
    24. finalStringtitle;
    25. @override
    26. _MyAppPageStatecreateState()=>_MyAppPageState();
    27. }
    28. class_MyAppPageStateextendsState<MyAppPage>{
    29. StringphoneNo;
    30. StringsmsOTP;
    31. StringverificationId;
    32. StringerrorMessage='';
    33. FirebaseAuth_auth=FirebaseAuth.instance;
    34. Future<void>verifyPhone()async{
    35. finalPhoneCodeSentsmsOTPSent=(StringverId,[intforceCodeResend]){
    36. this.verificationId=verId;
    37. smsOTPDialog(context).then((value){
    38. print('signin');
    39. });
    40. };
    41. try{
    42. await_auth.verifyPhoneNumber(
    43. phoneNumber:this.phoneNo,
    44. codeAutoRetrievalTimeout:(StringverId){
    45. this.verificationId=verId;
    46. },
    47. codeSent:
    48. smsOTPSent,
    49. timeout:constDuration(seconds:20),
    50. verificationCompleted:(AuthCredentialphoneAuthCredential){
    51. print(phoneAuthCredential);
    52. },
    53. verificationFailed:(AuthExceptionexceptio){
    54. print('${exceptio.message}');
    55. });
    56. }catch(e){
    57. handleError(e);
    58. }
    59. }
    60. Future<bool>smsOTPDialog(BuildContextcontext){
    61. returnshowDialog(
    62. context:context,
    63. barrierDismissible:false,
    64. builder:(BuildContextcontext){
    65. returnnewAlertDialog(
    66. title:Text('EnterSMSCode'),
    67. content:Container(
    68. height:85,
    69. child:Column(children:[
    70. TextField(
    71. onChanged:(value){
    72. this.smsOTP=value;
    73. },
    74. ),
    75. (errorMessage!=''
    76. ?Text(
    77. errorMessage,
    78. style:TextStyle(color:Colors.red),
    79. )
    80. :Container())
    81. ]),
    82. ),
    83. contentPadding:EdgeInsets.all(10),
    84. actions:<Widget>[
    85. FlatButton(
    86. child:Text('Done'),
    87. onPressed:(){
    88. _auth.currentUser().then((user){
    89. if(user!=null){
    90. Navigator.of(context).pop();
    91. Navigator.of(context).pushReplacementNamed('/homepage');
    92. }else{
    93. signIn();
    94. }
    95. });
    96. },
    97. )
    98. ],
    99. );
    100. });
    101. }
    102. signIn()async{
    103. try{
    104. finalAuthCredentialcredential=PhoneAuthProvider.getCredential(
    105. verificationId:verificationId,
    106. smsCode:smsOTP,
    107. );
    108. finalFirebaseUseruser=await_auth.signInWithCredential(credential);
    109. finalFirebaseUsercurrentUser=await_auth.currentUser();
    110. assert(user.uid==currentUser.uid);
    111. Navigator.of(context).pop();
    112. Navigator.of(context).pushReplacementNamed('/homepage');
    113. }catch(e){
    114. handleError(e);
    115. }
    116. }
    117. handleError(PlatformExceptionerror){
    118. print(error);
    119. switch(error.code){
    120. case'ERROR_INVALID_VERIFICATION_CODE':
    121. FocusScope.of(context).requestFocus(newFocusNode());
    122. setState((){
    123. errorMessage='InvalidCode';
    124. });
    125. Navigator.of(context).pop();
    126. smsOTPDialog(context).then((value){
    127. print('signin');
    128. });
    129. break;
    130. default:
    131. setState((){
    132. errorMessage=error.message;
    133. });
    134. break;
    135. }
    136. }
    137. @override
    138. Widgetbuild(BuildContextcontext){
    139. returnScaffold(
    140. appBar:AppBar(
    141. title:Text(widget.title),
    142. ),
    143. body:Center(
    144. child:Column(
    145. mainAxisAlignment:MainAxisAlignment.center,
    146. children:<Widget>[
    147. Padding(
    148. padding:EdgeInsets.all(10),
    149. child:TextField(
    150. decoration:InputDecoration(
    151. hintText:'EnterPhoneNumberEg.+910000000000'),
    152. onChanged:(value){
    153. this.phoneNo=value;
    154. },
    155. ),
    156. ),
    157. (errorMessage!=''
    158. ?Text(
    159. errorMessage,
    160. style:TextStyle(color:Colors.red),
    161. )
    162. :Container()),
    163. SizedBox(
    164. height:10,
    165. ),
    166. RaisedButton(
    167. onPressed:(){
    168. verifyPhone();
    169. },
    170. child:Text('Verify'),
    171. textColor:Colors.white,
    172. elevation:7,
    173. color:Colors.blue,
    174. )
    175. ],
    176. ),
    177. ),
    178. );
    179. }
    180. }

    Step 6

    When you successfully verify the OTP, you can check that Google Firebase stores the user details on the server. Please check the screenshot below.

      OTP Authentication In Flutter Using Firebase (8)


      Possible Errors

      Video: Flutter Firebase Authentication in Malayalam Part #1, Flutter App Development in India

      Error

      import androidx.annotation.NonNull;

      Solution

      Putandroid.useAndroidX=true

      android.enableJetifier=true

      Inandroid/gradle.properties file

      NOTE

      Please check the Git repository for the full source code. You need to add your google-services.json file in Android >> Apps folder.

      Conclusion

      OTP verification becomes one of the most required authentication techniques when security is very important. Google Firebase provides OTP Phone Authentication free starter plan and Flutter provides an easy to set up technique for this.

      Video: Flutter - Firebase authentication using OTP | Flutter web tutorials | FirebaseAuth

      Videos

      1. Flutter : Firebase Phone Authentication | OTP | flutter coding
      (amplifyabhi coding)
      2. Easy Flutter Firebase Phone Number Authentication - Flutter Chat App Firebase #4
      (KEYNOTECAST)
      3. Flutter - Let's work on the Phone Auth and OTP Screen || Flutter with Firebase #06 || Speed Coding
      (Dev Stack)
      4. Flutter - Authenticate with Firebase with a Phone Number Using Flutter || Flutter with Firebase #07
      (Dev Stack)
      5. Flutter Firebase Phone Authentication
      (Code Base Tutorials)

      You might also like

      Latest Posts

      Article information

      Author: Jeremiah Abshire

      Last Updated: 05/04/2022

      Views: 6379

      Rating: 4.3 / 5 (54 voted)

      Reviews: 93% of readers found this page helpful

      Author information

      Name: Jeremiah Abshire

      Birthday: 1993-09-14

      Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

      Phone: +8096210939894

      Job: Lead Healthcare Manager

      Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

      Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.