Phone Authentication using Firebase in Flutter

Step 1 : In order to use Phone Authentication in Flutter using Firebase we have to create a project in Firebase Console and provide any name of project like below:

Open Firebase Console

Step 2 : Then simply click on continue button.

Step 3 : Choose defaut account for firebase then click on create project button.

Step 4 : Now your project is creating.

Step 5 : After creating your project click on continue button.

Step 6 : Now select platform where you want to add Firebase. In my case i just selected Android.

Step 7 : Now you have to provide some details about your application. Firstly you need to provide your application package name that you can get from AndroidManifest.xml file and SHA1 fingreprint. So you have to create a Flutter project then you can get package name like below:

Step 8 :For getting SHA 1 fingreprint you have to go to the Android Studio Terminal and write below command and press enter like below:

Step 9 : After this command you can get SHA 1 key like below:

Step 10 : Now you can write package name and SHA 1 Fingreprint here then click on Register App.

Step 11 : Download google-service.json file.

Step 12 : After downloading google-service.json file then you need to click continue to the console.

Step 13 : Enable Phone from Sign-in-method in Authentication panel like below:

Step 14 : Now you need to paste google-service.json file inside your_project->android->app->google-service.json like below:

Step 15 : Add classpath inside your_project->android->build.gradle like below:

classpath 'com.google.gms:google-services:4.2.0'

Step 16 : Apply plugin inside your_project->android->app->build.gradle like below:

apply plugin: 'com.google.gms.google-services'

Step 17 : Add dependency inside your_project->android->app->build.gradle like below:

        dependencies {
        implementation platform('com.google.firebase:firebase-bom:26.8.0')
        implementation "androidx.browser:browser:1.3.0"
        implementation 'com.google.firebase:firebase-analytics'
        }

Step 18 : Add following plugins in pubspeck.yaml file like below:

        firebase_auth: ^1.1.4
        firebase_core: ^1.1.1
    

main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:phone_auth/splash.dart';

void main() async{

//All Firebase versions have been updated 
//and now you have to call Firebase.initializeApp()
//before using any Firebase product
  
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  
  runApp(MyApp());
  
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Phone Authentication',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SplashScreen(),
    );
  }
}

splash.dart

import 'package:flutter/material.dart';
import 'package:phone_auth/loginscreen.dart';

class SplashScreen extends StatefulWidget {

  @override
  _SplashScreenState createState() => _SplashScreenState();
  
}

class _SplashScreenState extends State<SplashScreen> {

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(seconds: 5), () {
      setState(() {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => LoginScreen(),
            ));
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Splash Screen"),
      ),
      body: Container(
        child: Center(
          child: Image(
            image: NetworkImage(
                "https://...b.gif"),
            width: 200,
            height: 200,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

}

loginscreen.dart

import 'package:flutter/material.dart';
import 'package:phone_auth/otpscreen.dart';

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  TextEditingController tnumber = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Login Screen"),
      ),
      body: Container(
        child: Column(
          children: [
            SizedBox(
              height: 50,
            ),
            Icon(
              Icons.call,
              size: 100,
              color: Colors.blue,
            ),
            Text(
              "Phone Authentication",
              style: TextStyle(
                  fontFamily: "serif",
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue),
            ),
            SizedBox(
              height: 30,
            ),
            Container(
              margin: EdgeInsets.all(10),
              child: TextField(
                controller: tnumber,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: "Enter Phone Number",
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 40,
            ),
            ElevatedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => OtpScreen(tnumber.text),
                    ),
                  );
                },
                child: Text("Submit Here")),
          ],
        ),
      ),
    );
  }
}

otpscreen.dart

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

class OtpScreen extends StatefulWidget {
  String phone;

  OtpScreen(this.phone);

  @override
  _OtpScreenState createState() => _OtpScreenState();
}

class _OtpScreenState extends State<OtpScreen> {
  TextEditingController tcode = TextEditingController();
  String verificationcode = "";

  @override
  void initState() {
    super.initState();
    verifyPhoneNumber();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("OTP Screen"),
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        child: Column(
          children: [
            SizedBox(
              height: 50,
            ),
            Icon(
              Icons.sms,
              size: 100,
              color: Colors.blue,
            ),
            Text(
              "Enter OTP Code Here",
              style: TextStyle(
                  fontFamily: "serif",
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue),
            ),
            SizedBox(
              height: 30,
            ),
            Container(
              margin: EdgeInsets.all(10),
              child: TextField(
                controller: tcode,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: "Enter OTP Number",
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 40,
            ),
            ElevatedButton(
                onPressed: () {
                  FirebaseAuth.instance
                      .signInWithCredential(PhoneAuthProvider.credential(
                          verificationId: verificationcode,
                           smsCode: tcode.text))
                      .then((value) {
                    if (value.user != null) {
                      //go to home page
                      Navigator.pop(context);
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => HomeScreen(value.user),
                          ));
                    }
                  });
                },
                child: Text("Verify and Login")),
          ],
        ),
      ),
    );
  }

  verifyPhoneNumber() {
    FirebaseAuth.instance.verifyPhoneNumber(
      phoneNumber: "${widget.phone}",
      verificationCompleted: (phoneAuthCredential) {
        print("${widget.phone}");
        FirebaseAuth.instance
            .signInWithCredential(phoneAuthCredential)
            .then((value) {
          if (value.user != null) {
            print("user is logged in");
          }
        });
      },
      verificationFailed: (error) {
        print(error.message);
      },
      codeSent: (verificationId, forceResendingToken) {
        setState(() {
          verificationcode = verificationId;
          print(verificationcode);
        });
      },
      codeAutoRetrievalTimeout: (verificationId) {
        setState(() {
          verificationcode = verificationId;
        });
      },
      timeout: Duration(seconds: 60),
    );
  }
}

home.dart

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

class HomeScreen extends StatefulWidget {
  User user;

  HomeScreen(this.user);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Home Screen"),
          leading: Icon(Icons.menu),
        ),
        body: Container(
          child: Column(
            children: [
              SizedBox(
                height: 20,
              ),
              Center(child: Text("Welcome Home Page",
              style: TextStyle(fontSize: 20),)),
              
              SizedBox(height: 30,),
              
              Text(widget.user.phoneNumber),
              Text(widget.user.uid),
              
              SizedBox(height: 30,),
              
              ElevatedButton(onPressed: (){
                setState(() {
                  User user=FirebaseAuth.instance.currentUser;
                  if(user!=null){
                    user=null;
                    Navigator.pop(context);
                    Navigator.push(context, 
                    MaterialPageRoute(builder: (context) => LoginScreen(),));
                  }
                });
              }, child: Text("Logout")),

            ],
          ),
        ));
  }
}

No comments: