Ask Your Question
3

How to implement Flutter's SMS One-Time Password (OTP) verification process after a user registers using their email?

asked 2022-09-12 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-11-30 08:00:00 +0000

huitzilopochtli gravatar image
  1. First, we need to add the necessary dependencies to our project. In the pubspec.yaml file, add the following:
dependencies:
  sms_otp_auto_verify: ^0.2.0
  firebase_auth: ^0.18.4+1
  1. Next, we need to set up Firebase Authentication in our Flutter project. Follow the official documentation here to set up Firebase Authentication.

  2. Once Firebase Authentication is set up, we can use the Firebase Authentication API to send the SMS OTP message to the user's phone number. To do this, we'll create a function called sendSMSOTP():

import 'package:firebase_auth/firebase_auth.dart';

Future<void> sendSMSOTP(String phone) async {
  final PhoneVerificationCompleted verificationCompleted =
      (AuthCredential phoneAuthCredential) {
    FirebaseAuth.instance.signInWithCredential(phoneAuthCredential);
  };

  final PhoneVerificationFailed verificationFailed =
      (FirebaseAuthException authException) {
    print('Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
  };

  final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) async {
    // Save the verification ID somewhere as it will be needed to authenticate the user later
    print('Verification code sent to ${phone}. Verification ID: ${verificationId}');
  };

  final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
      (String verificationId) {
    // Save the verification ID somewhere as it will be needed to authenticate the user later
    print('Auto retrieval timeout. Verification ID: ${verificationId}');
  };

  await FirebaseAuth.instance.verifyPhoneNumber(
    phoneNumber: phone,
    verificationCompleted: verificationCompleted,
    verificationFailed: verificationFailed,
    codeSent: codeSent,
    codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
  );
}
  1. Now we need to create a UI for the user to enter their phone number and receive the verification code. We'll create a simple UI with a text field to enter the phone number and a button to send the SMS:
import 'package:flutter/material.dart';
import 'package:sms_otp_auto_verify/sms_otp_auto_verify.dart';

class SMSVerificationScreen extends StatefulWidget {
  @override
  _SMSVerificationScreenState createState() => _SMSVerificationScreenState();
}

class _SMSVerificationScreenState extends State<SMSVerificationScreen> {
  final TextEditingController _phoneNumberController = TextEditingController();
  String _smsCode = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SMS Verification'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                controller: _phoneNumberController,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  hintText: 'Enter your phone number',
                ),
              ),
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              child: Text('Send SMS'),
              onPressed: () async {
                await sendSMSOTP(_phoneNumberController.text);
              },
            ),
            SizedBox(height: 16.0),
            Text('Enter the SMS code below:'),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: PinFieldAutoFill(
                codeLength: 6,
                onCodeChanged: (String code) {
                  setState(() {
                    _smsCode = code;
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
  1. Finally, we need to verify the user's phone number by comparing the SMS code they entered to the SMS code sent by Firebase Authentication. We'll create another function called verifySMS():
import 'package:firebase_auth/firebase_auth.dart';

Future<bool> verifySMS(String smsCode) async {
  bool verified = false;

  final PhoneAuthCredential credential = PhoneAuthProvider.credential(
    verificationId: verificationId,
    smsCode: smsCode,
  );

  try {
    await FirebaseAuth.instance.signInWithCredential(credential);
    verified = true;
  } catch (e) {
    print('Could not verify SMS code: ${e.toString()}');
    verified = false;
  }

  return verified;
}
  1. We can now call the verifySMS() function when the user submits the SMS verification code. If the code is correct, we can allow the user to continue using the app. If the code is incorrect, we can show an error message and ask the user to try again.
ElevatedButton(
  child: Text('Verify SMS'),
  onPressed: () async {
    if (await verifySMS(_smsCode)) {
      // SMS verification successful, allow user to continue using the app
    } else {
      // ...
(more)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-12 11:00:00 +0000

Seen: 8 times

Last updated: Nov 30 '21