Sunday, June 4, 2023

Build a Secure Flutter App with Phone Authentication OTP using Firebase

 Here's an example of a Flutter app with phone authentication OTP feature using Firebase


Set up Firebase:

  • Create a new Flutter project.

  • Set up Firebase in your project by following the instructions in the Firebase documentation.

  • Add the necessary Firebase dependencies to your pubspec.yaml file.

Import required packages:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

Create a stateful widget for your app: 

class PhoneAuthApp extends StatefulWidget {
  @override
  _PhoneAuthAppState createState() => _PhoneAuthAppState();
}

class _PhoneAuthAppState extends State<PhoneAuthApp> {
  FirebaseAuth _auth = FirebaseAuth.instance;
  String _verificationId = '';
  String _phoneNumber = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Phone Authentication'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Enter your phone number:',
              ),
              TextField(
                onChanged: (value) {
                  setState(() {
                    _phoneNumber = value;
                  });
                },
              ),
              ElevatedButton(
                child: Text('Send OTP'),
                onPressed: () {
                  _verifyPhoneNumber();
                },
              ),
              TextField(
                onChanged: (value) {
                  setState(() {
                    _verificationId = value;
                  });
                },
              ),
              ElevatedButton(
                child: Text('Verify OTP'),
                onPressed: () {
                  _signInWithPhoneNumber();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _verifyPhoneNumber() async {
    PhoneVerificationCompleted verificationCompleted =
        (PhoneAuthCredential phoneAuthCredential) async {
      await _auth.signInWithCredential(phoneAuthCredential);
      // Verification completed, proceed to next steps like signing in
      // or displaying user information.
    };

    PhoneVerificationFailed verificationFailed =
        (FirebaseAuthException authException) {
      // Handle verification failure.
    };

    PhoneCodeSent codeSent =
        (String verificationId, [int? forceResendingToken]) async {
      // Save the verification ID and resend token to use them later
      _verificationId = verificationId;
    };

    PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
        (String verificationId) {
      // Auto-resolution timed out, handle the error.
    };

    await _auth.verifyPhoneNumber(
      phoneNumber: _phoneNumber,
      verificationCompleted: verificationCompleted,
      verificationFailed: verificationFailed,
      codeSent: codeSent,
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
    );
  }

  Future<void> _signInWithPhoneNumber() async {
    PhoneAuthCredential credential = PhoneAuthProvider.credential(
      verificationId: _verificationId,
      smsCode: _smsCode,
    );

    await _auth.signInWithCredential(credential);
    // Sign in success, proceed to next steps like displaying user information.
  }
}

Run the app: 

  • Update your main.dart file to run the PhoneAuthApp widget as the home.

  • Run the app on a simulator or a physical device.

 

No comments:

Post a Comment

Enhancing Flutter Apps with BLoC State Management and REST APIs for Optimal Performance

 Develop a powerful Flutter app utilizing BLoC state management and REST APIs to enhance functionality and performance. Flutter app using th...