Code Monkey home page Code Monkey logo

weblineindia / flutter-otp-authentication Goto Github PK

View Code? Open in Web Editor NEW
251.0 11.0 38.0 258 KB

A Flutter based OTP Authentication component, used to verify your mobile number with OTP (One Time Password) using Firebase Authentication.

Home Page: https://www.weblineindia.com/software-development-resources.html

License: MIT License

Kotlin 1.39% Ruby 4.47% Swift 1.34% Objective-C 0.12% Dart 92.68%
flutter flutter-demo flutter-components flutter-examples flutter-plugin reusable-components flutter-library flutter-otp otp-authentication flutter-otp-authentication

flutter-otp-authentication's Introduction

Flutter - OTP Authentication

A Flutter based OTP Authentication component, used to verify your mobile number with OTP (One Time Password) using Firebase Authentication.

Table of contents

Flutter Support

Version - Flutter 1.17 (stable)

We have tested our program in above version, however you can use it in other versions as well.

Demo


Features

  • Select country with flag & country code.
  • Verify mobile number with OTP all over the world.

Getting started

  • Download this sample project and import widget dart files in your Flutter App.
  • Update Widgets UI based on your requirements.

Usage

Setup process is described below to integrate in sample project.

Methods

Configure Firebase in main method.

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();

Configure Country Picker Widget & implement method for call back selected country details e.g

// Put CountryPicker Widget
CountryPicker(
    callBackFunction: _callBackFunction
);
   
// Create callback function 
void _callBackFunction(String name, String dialCode, String flag) {
    // place your code
}

Configure OtpPinField For OTP (One Time Password)

// add these packages in pubspec.yaml file
otp_pin_field: ^1.2.2
firebase_core: ^2.25.4
   
// run this command to install package
flutter pub get
   
// initialize key and add OtpPinField in class

final _otpPinFieldKey = GlobalKey<OtpPinFieldState>();

OtpPinField(
  key: _otpPinFieldKey,
  textInputAction: TextInputAction.done,
  maxLength: 6,
  fieldWidth: 40,
  onSubmit: (text) {
        smsOTP = text;
  },
  onChange: (text) {}
)

Validate Phone Number & Generate Otp

// generate otp method and store Verification Id
Future<void> 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);
 }
}

Verify otp

//Method for verify otp entered by user  
Future<void> verifyOtp() async {
   if (smsOTP.isEmpty || smsOTP == '') {
      showAlertDialog(context, 'please enter 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');
        }
  }

Handle errors

//Method for handle the errors
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;
  }
}

Directive options

Firebase project setup steps

Create Project setup in firebase console using below URL https://console.firebase.google.com/ . Enable Phone Number sign-in for your Firebase project in console https://firebase.google.com/docs/auth/ios/phone-auth

Download GoogleService-Info.Plist file and add into iOS folder

Download GoogleService.json file and add into Android folder

Firebase project setup steps

Install following pub dev package

firebase_auth: ^0.15.4


Want to Contribute?

  • Created something awesome, made this code better, added some functionality, or whatever (this is the hardest part).
  • Fork it.
  • Create new branch to contribute your changes.
  • Commit all your changes to your branch.
  • Submit a pull request.

Collection of Components

We have built many other components and free resources for software development in various programming languages. Kindly click here to view our Free Resources for Software Development.


Changelog

Detailed changes for each release are documented in CHANGELOG.

License

MIT

Keywords

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

flutter-otp-authentication's People

Contributors

partners-wli avatar sxmeer-ahmed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.