Open In App

Firebase Authentication with Phone Number OTP in Flutter Web

Last Updated : 23 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Phone number verification using Firebase in the Flutter Web app can be done by sending OTP SMS to the phone number. The user will enter the OTP in the message and will easily sign in to his/her account. We are going to implement it in Flutter Web.

Step by Step implementation

Step 1: Create a new Flutter app in Android Studio

Open Android Studio -> Go to New Flutter Project -> Select Flutter in the left tab and Flutter SDK Path and go to Next. Specify the project name, project location, and project type as Application, and select Web also in the Platforms section. Click on Finish. You can see a directory named Web is now created along with all the directories.

Step 2: Create a web app in Firebase

Create a Firebase project in the Firebase Console. In Project Overview, go to Web.

 

Set a web app name -> Click on Register App. In the Add Firebase SDK section, copy the following code.

 

Step 3: 

Create a phoneOTPVerification.dart file in the lib directory and refer to the following code.

Dart




import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
  
class PhoneOTPVerification extends StatefulWidget {
  const PhoneOTPVerification({Key? key}) : super(key: key);
  
  @override
  State<PhoneOTPVerification> createState() => _PhoneOTPVerificationState();
}
  
class _PhoneOTPVerificationState extends State<PhoneOTPVerification> {
  TextEditingController phoneNumber = TextEditingController();
  TextEditingController otp = TextEditingController();
  bool visible = false;
  var temp;
  
  @override
  void dispose() {
    phoneNumber.dispose();
    otp.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Phone OTP Authentication"),
      ),
      body: SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            inputTextField("Contact Number", phoneNumber, context),
            visible ? inputTextField("OTP", otp, context) : SizedBox(),
            !visible ? SendOTPButton("Send OTP") : SubmitOTPButton("Submit"),
          ],
        ),
      ),
    );
  }
  
  Widget SendOTPButton(String text) => ElevatedButton(
    onPressed: () async {
      setState(() {visible = !visible;});
      temp = await FirebaseAuthentication().sendOTP(phoneNumber.text);
    },
    child: Text(text),
  );
  
  Widget SubmitOTPButton(String text) => ElevatedButton(
    onPressed: () =>FirebaseAuthentication().authenticate(temp, otp.text),
    child: Text(text),
  );
  
  Widget inputTextField(String labelText, TextEditingController textEditingController, BuildContext context) =>
    Padding(
      padding: EdgeInsets.all(10.00),
      child: SizedBox(
        width: MediaQuery.of(context).size.width / 1.5,
        child: TextFormField(
          obscureText: labelText == "OTP" ? true : false,
          controller: textEditingController,
          decoration: InputDecoration(
            hintText: labelText,
            hintStyle: TextStyle(color: Colors.blue),
            filled: true,
            fillColor: Colors.blue[100],
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
              borderRadius: BorderRadius.circular(5.5),
            ),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
              borderRadius: BorderRadius.circular(5.5),
            ),
          ),
        ),
      ),
    );
}
  
class FirebaseAuthentication {
  String phoneNumber = "";
  
  sendOTP(String phoneNumber) async {
    this.phoneNumber = phoneNumber;
    FirebaseAuth auth = FirebaseAuth.instance;
    ConfirmationResult result = await auth.signInWithPhoneNumber(
      '+91$phoneNumber',
    );
    printMessage("OTP Sent to +91 $phoneNumber");
    return result;
  }
  
  authenticate(ConfirmationResult confirmationResult, String otp) async {
    UserCredential userCredential = await confirmationResult.confirm(otp);
    userCredential.additionalUserInfo!.isNewUser
        ? printMessage("Authentication Successful")
        : printMessage("User already exists");
  }
  
  printMessage(String msg) {
    debugPrint(msg);
  }
}


Step 4: 

Go to the index.html file in the web directory and write the following code inside the body tag. As we are working with the web, we only need to make changes in the index.html. We don’t need to download the google-services.json file.

HTML




  
  <script>
    // paste the code copied 
    // from Firebase SDK below.
    const firebaseConfig = {
      apiKey: "",
      authDomain: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: "",
      appId: "",
      measurementId: ""
    };
  
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
      
  </script>


Step 5: 

Go to main.dart file in lib and initialize Firebase in the main file.

Dart




import 'package:authe/phoneOTPVerification.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
  
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
      // paste the code copied
      // from Firebase SDK below.
      options: const FirebaseOptions(
          apiKey: "",
          authDomain: "",
          projectId: "",
          storageBucket: "",
          messagingSenderId: "",
          appId: "",
          measurementId: "")
  );
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the 
  // root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PhoneOTPVerification(),
    );
  }
}


Step 6: 

Select a device as Chrome (web) or Edge (web) as per your choice. Then Run the application. Enter the contact number and click on Send OTP button. OTP will be sent to the entered contact number. Enter it in the OTP input field and click on Submit button. 

Output Video:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads