Flutter Firebase User Authentication Using Phone Number
Tags: flutter, programming, firebase
Published: 2022-12-21 15:03:28

In the context of security, there are different reliable methods available that many people utilize while working on apps. Since data security is a significant concern for many people, app developers and programmers heavily focus on user identity authentication services. One of the most usable processes in this require is phone number-based authentication.  

Indeed, this is one of the most notable processes since the user verification method through phone numbers is secure and fast. Typically, when users try to carry out any online interaction, the number verification sequence occurs where the user receives an SMS message with the OTP. If the phone number one put in for the verification is accurate, the code passes through properly, and users can access their app data. 

In this context, , working with Firebase AUTH, and you should understand how to utilize that properly for Flutter user authentication.

The following are the common steps that go into the procedure. 

##Setup Phase 

Before beginning the phone authentication process, one must handle the following steps. 

Firstly, enable the phone as your preferred sign-in mode in the Firebase console.

In iOS devices, you must activate push notifications in Xcode for the project and activate the Firebase Cloud Messaging (FCM) configuration with the APNs authentication key. 

If you have not completed the SHA-1 hash setup on your app in the Firebase console while using your Android phone, you should handle the process first. 

While using the web-based routes, you should include the app domains under OAuth redirect domains in the Firebase console.
 
##Add Firebase Auth into Flutter Phase 

You have to insert the dependency for Firebase Auth into the available “pubspec.yaml” file:

```
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  firebase_auth: ^1.2.0
  firebase_core: ^1.2.0

```
Then, you have to hit the Ctrl + S keys on your keyboard to save the dependencies into the Flutter app. Make sure that null safety is enabled while doing this process. 

Activate Phone Authentication within Firebase 
You must enable the Safety Net first and get the SHA-1 and SHA-256 keys. The commands for that are:

```
cd android
./gradlew signingReport
```

Next, copy the keys and reach the Firebase console. Access the Project settings and add the key details properly. Following this, install the google-services.json once more and include it under android/app to the project. 

Reach the Firebase console next and activate the Phone authentication function. Go to the tab for Authentication and tap on the Sign-in method. Multiple providers will appear as options next for you to choose from. 

##Prepare the Phone Authentication Form 

You have to prepare the PhoneAuthForm class using the Form widget. Then, assign this class to the FormState type’s GlobalKey. Next, you must prepare two TextFormFields and operate the TextEditingController to obtain the input text via the “text” property. This will create two screens- click on the sign-in process with any provider and go to the OTP verification screen. 

##Manage the Main Phone Authentication Process 

You have to validate the available form state within the “onPressed” callback and then transform the “isLoading” value into “true”. This will cause a CircularProgressIndicator() to replace the available button. The developer has to call the phoneSignIn() next. 

The verifyPhoneNumber() mode working within the firebase_auth dependency will progress with the OTP generation. This will then get sent to the device via many callbacks. 

Two cases will occur, and the “verificationCompleted” mode will get invoked then. 

###1. Auto-retrieval

In some devices, Google Play Services can automatically perceive the incoming verification SMS and proceed with the verification process without the user having to make any moves. 

###2. Instant Verification

In particular devices, the verification process for the phone number occurs instantly without the user having to add a verification code. 

The callback here will consider PhoneAuthCredential in the form of an argument. This will have the smsCode. 

Following this, working on the case will update the value in the TextFormField that holds the OTP using setState(). 

At this point, since the user is signed into the system already, the next step is to utilize linkWithCredential() to connect the phone and the credential of another provider. If the error “e.code == ‘provider-already-linked’” comes up next, the linking will occur automatically. 

Next, the user must sign in and move to the HomePage(). In the future, whenever there is an error, the algorithm will arrange a callback for the “verificationFailed” option. Thus, when you hire a development team they will mention the importance of adding a showMessage() for displaying the error each time to the main user. 

When the system sends the SMS verification code to the phone number, a codeSent callback occurs. Developers save the available verificationId after that to prepare a credential at a later time, combining the verification ID with the code.

Without any state management, we can write the code below

###Sample Code

```dart
Future<bool> signIn() async {
  try {
    final AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    final AuthResult userResult = await _auth.signInWithCredential(credential);
    final FirebaseUser currentUser = await _auth.currentUser();
 
    final document = Firestore().collection("users").document(currentUser.uid);
    final documentSnapshot = await document.get();
    if (!documentSnapshot.exists) {
      await document.setData({
        "id": currentUser.uid,
        "number": phoneNumber,
      });
    }
    return true;
  } catch (e) {
    return false;
  }
}
</bool>
From the UI call with credentials, Add onPressed function of a button below:

onPressed: () async {
  if (_smsController.text.isEmpty) {
    widget.scaffoldKey.currentState
        .showSnackBar(SnackBar(
      content: Text(
          "Please enter your SMS code"),
      duration: Duration(seconds: 2),
    ));
    return;
  }
 
  await _auth
      .currentUser()
      .then((user) async {
    await signIn()
        .then((bool isSignedIn) async {
      if (isSignedIn) {
        Navigator.of(context)
            .pushAndRemoveUntil();
      } else {
        widget.scaffoldKey.currentState
            .showSnackBar(SnackBar(
          content:
              Text("Incorrect Code"),
          duration:
              Duration(seconds: 2),
        ));
      }
    });
  });
},
```

##Adding the User Information

If login using a phone number then the only field available in the user object will be phone number. To add the other details you have to use the firebase auth functions.

```dart
reload()
unlink()
updateEmail()
updatePassword()
updatePhoneNumber()
updateProfile()
eg:  user.updateEmail(“sample.sample.com”);
```

##Retrieving the User Information Phase 

Following the previous stage, developers must prepare a new file named “home_page.dart” which shall hold the HomePage class. You have the make the next callback command to retrieve the user currently available:

```dart
User? user = FirebaseAuth.instance.currentUser;
Add the necessary widgets within the Column widget next:
body: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <widget>[
            Text(user!.email!),
            Text(user!.displayName!),
            CircleAvatar(
              backgroundImage: NetworkImage(user!.photoURL!),
              radius: 20,
            )
          ],
        )))
</widget>
```

These steps are useful for retrieving the name, email id, and photo URL that the user owns. 

On the next screen, the app bar will also showcase the logout button. The method here is identified as “service.signOutFromGoogle();” within the FirebaseService class.

##Wrapping Up
 
Indeed, with the right steps, one can activate the user authentication functionality on Flutter based on phone numbers. So, we have learned all the right steps for user authentication using the phone number in Flutter. While proceeding with this authentication, firebase will become the crucial part. You can share your doubts, queries and suggestion in the comment section.


##Frequently Asked Questions (FAQs)

**1. How to use phone authentication on Flutter development?**

The Firebase authentication SDK for the Flutter framework manages the ReCaptcha widget out of the box by default. However, it offers control over how it is displayed and configured if needed. To begin, call the signInWithPhoneNumber method with the phone number. FirebaseAuth auth = FirebaseAuth.

**2. How can I send OTP to the mobile using Flutter?**

You can now add the FirebasePhoneAuthHandler widget to the widget tree and pass all the necessary parameters to begin. The phone number is the number to which an OTP is sent in a particular format.

**3. How does the authentication work in Flutter?**

In the authentication provider, you are required to enable it in the Firebase console. Go to the Sign-in Method page in the Firebase Authentication section to help Email or sign in with the other identity providers you wish into your application.