Firebase auth in Flutter

Screenshot-2023-03-06-at-13.37.15

Firebase auth in Flutter is a Flutter plugin that simplifies Firebase user authentication. It makes authenticating users using email and password, phone number, Google, Facebook, Twitter, and other popular authentication providers easy.

Firebase auth in Flutter lets you rapidly and securely authenticate users and manage their accounts in your Flutter app. It provides APIs for managing user authentication status, creating and managing user accounts, and managing user profile information.

With Firebase Auth Flutter, you can:

  • Use email and password, phone number, Google, Facebook, Twitter, and other popular authentication sources to verify users.
  • Save user authentication state and credentials across app restarts.
  • Make new accounts for people and take care of administrative tasks like password changing and email verification.
  • Manage a user’s profile information, like their display name, photo URL, and custom user properties.

The Firebase suite of solutions, of which Firebase auth in Flutter is a part, offers a complete toolkit for rapidly developing high-quality apps. You can manage user authentication and accounts in your Flutter app with ease thanks to Firebase Auth Flutter.

To use Firebase auth in Flutter with Google sign-in in Flutter, follow these steps:

Firebase auth in Flutter
  1. Add the following packages to your pubspec.yaml file: dependencies: firebase_auth: ^4.4.0 google_sign_in: ^5.1.1
  2. In your Firebase console, enable Google sign-in by going to Authentication > Sign-in methods and enabling Google as a sign-in provider.
  3. In your Flutter app, initialize Firebase:
    import 'package:firebase_core/firebase_core.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    
  4. Create a GoogleSignIn object and configure it with your Firebase project’s client ID:
    import 'package:google_sign_in/google_sign_in.dart';
    
    final GoogleSignIn googleSignIn = GoogleSignIn(
      scopes: <String>[
        'email',
      ],
    );
    
  5. Create a Firebase auth instance:
    import 'package:firebase_auth/firebase_auth.dart';
    
    final FirebaseAuth _auth = FirebaseAuth.instance;
    
  6. In your login screen, create a button that will trigger the Google sign-in process:
  7. RaisedButton( onPressed: () async { final GoogleSignInAccount googleUser = await googleSignIn.signIn(); final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); final UserCredential userCredential = await _auth.signInWithCredential(credential); final User user = userCredential.user; // TODO: Navigate to home screen }, child: Text(‘Sign in with Google’), )

    This code will prompt the user to select a Google account and authorize your app to access their email address. Once the user has authorized your app, the signInWithCredential method will sign them in to Firebase with their Google account.

  8. When the user signs out, call the signOut method on the GoogleSignIn object:
    await googleSignIn.signOut();
    

    This will sign the user out of both Firebase and Google.

Complete example of implementing Firebase auth in Flutter with Google sign-in in Flutter:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn(
  scopes: <String>[
    'email',
  ],
);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase Auth with Google Sign-in',
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () async {
            final GoogleSignInAccount googleUser = await googleSignIn.signIn();
            final GoogleSignInAuthentication googleAuth =
                await googleUser.authentication;
            final AuthCredential credential = GoogleAuthProvider.credential(
              accessToken: googleAuth.accessToken,
              idToken: googleAuth.idToken,
            );
            final UserCredential userCredential =
                await _auth.signInWithCredential(credential);
            final User user = userCredential.user;
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => HomePage()),
            );
          },
          child: Text('Sign in with Google'),
        ),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () async {
            await googleSignIn.signOut();
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (context) => LoginPage()),
              (route) => false,
            );
          },
          child: Text('Sign out'),
        ),
      ),
    );
  }
}

The LoginPage used here only has one button on it, and clicking it begins the Google sign-in procedure. After successfully logging in, the user is redirected to the HomePage, where they will find a sign-out link. The LoginPage is reloaded when a user logs out.

You should add more features and error handling to your own implementation because this is only a simple example.

Authenticate users with email and password

To authenticate users with email and password using Firebase auth in Flutter app, follow these steps:

  • Add the following package to your pubspec.yaml file:
dependencies:
  firebase_auth: ^4.4.0
  • Initialize Firebase in your Flutter app:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
  • import ‘package:firebase_core/firebase_core.dart’; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }
  • Create a FirebaseAuth instance:
    import 'package:firebase_auth/firebase_auth.dart';
    
    final FirebaseAuth _auth = FirebaseAuth.instance;
    
  • To create a new user with an email and password, call the createUserWithEmailAndPassword method on the FirebaseAuth instance:
    try {
      final UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      final User user = userCredential.user;
      // TODO: Navigate to home screen or perform other actions with the user information
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        print('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');
      }
    } catch (e) {
      print(e);
    }
    

    This code will create a new user with the specified email and password. If the email is already in use, the createUserWithEmailAndPassword method will throw a FirebaseAuthException with the email-already-in-use error code. If the password is too weak, it will throw an exception with the weak-password error code.

  • To sign in an existing user with their email and password, call the signInWithEmailAndPassword method on the FirebaseAuth instance:
    try {
      final UserCredential userCredential = await _auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      final User user = userCredential.user;
      // TODO: Navigate to home screen or perform other actions with the user information
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('Wrong password provided for that user.');
      }
    } catch (e) {
      print(e);
    }
    

    This code will sign in an existing user with the specified email and password. If no user is found for the specified email, the signInWithEmailAndPassword method will throw a FirebaseAuthException with the user-not-found error code. If the password is incorrect, it will throw an exception with the wrong-password error code.

Note that you’ll need to handle errors and exceptions appropriately in your own code, and you may also want to provide UI elements for users to enter their email and password.

Authenticate users with phone number

To authenticate users with phone number using Firebase auth in Flutter app, follow these steps:

  1. Add the following package to your pubspec.yaml file:
    dependencies:
      firebase_auth: ^3.1.0
    
  2. Initialize Firebase in your Flutter app:
    import 'package:firebase_core/firebase_core.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    
  3. Create a FirebaseAuth instance:
    import 'package:firebase_auth/firebase_auth.dart';
    
    final FirebaseAuth _auth = FirebaseAuth.instance;
    
  4. To authenticate a user with their phone number, call the verifyPhoneNumber method on the FirebaseAuth instance:
    void _verifyPhoneNumber() async {
      await _auth.verifyPhoneNumber(
        phoneNumber: phoneNumber,
        verificationCompleted: (PhoneAuthCredential credential) async {
          final UserCredential userCredential = await _auth.signInWithCredential(credential);
          final User user = userCredential.user;
          // TODO: Navigate to home screen or perform other actions with the user information
        },
        verificationFailed: (FirebaseAuthException e) {
          if (e.code == 'invalid-phone-number') {
            print('The provided phone number is not valid.');
          } else {
            print('Failed to verify phone number: ${e.message}');
          }
        },
        codeSent: (String verificationId, int resendToken) async {
          // Save the verification ID and resend token to use later
          _verificationId = verificationId;
          _resendToken = resendToken;
        },
        codeAutoRetrievalTimeout: (String verificationId) {
          // Auto-retrieval timed out
          _verificationId = verificationId;
        },
        timeout: Duration(seconds: 60),
      );
    }
    

    This code will send a verification code to the specified phone number and handle the verification process. The verificationCompleted callback will be called if the verification is successful, and the verificationFailed callback will be called if the verification fails. The codeSent callback will be called when the verification code is sent, and the codeAutoRetrievalTimeout callback will be called if the code is not automatically retrieved within the specified timeout.

  5. To sign in with a verification code, call the signInWithCredential method on the FirebaseAuth instance with a PhoneAuthCredential:
    void _signInWithPhoneNumber(String verificationCode) async {
      final PhoneAuthCredential credential = PhoneAuthProvider.credential(
        verificationId: _verificationId,
        smsCode: verificationCode,
      );
      final UserCredential userCredential = await _auth.signInWithCredential(credential);
      final User user = userCredential.user;
      // TODO: Navigate to home screen or perform other actions with the user information
    }
    

    This code will sign in the user with the specified verification code. Note that you’ll need to store the verification ID and resend token from the codeSent callback in order to verify the code later.

Note that you’ll need to handle errors and exceptions appropriately in your own code, and you may also want to provide UI elements for users to enter their phone number and verification code.

Authenticate users with Google

To authenticate users with Google using Firebase auth in Flutter app, follow these steps:

  1. Add the following packages to your pubspec.yaml file:
    dependencies:
      firebase_auth: ^3.1.0
      google_sign_in: ^5.1.1
    
  2. Initialize Firebase in your Flutter app:
    import 'package:firebase_core/firebase_core.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    
  3. Create a FirebaseAuth instance and a GoogleSignIn instance:
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:google_sign_in/google_sign_in.dart';
    
    final FirebaseAuth _auth = FirebaseAuth.instance;
    final GoogleSignIn googleSignIn = GoogleSignIn(
      scopes: <String>[
        'email',
      ],
    );
    
  4. To sign in with Google, call the signIn method on the GoogleSignIn instance:
    try {
      final GoogleSignInAccount googleUser = await googleSignIn.signIn();
      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );
      final UserCredential userCredential = await _auth.signInWithCredential(credential);
      final User user = userCredential.user;
      // TODO: Navigate to home screen or perform other actions with the user information
    } catch (e) {
      print(e);
    }
    

    This code will prompt the user to select a Google account and authorize your app to access their email address. Once the user has authorized your app, it will sign them in to Firebase with their Google account.

  5. To sign out, call the signOut method on the GoogleSignIn instance:
    await googleSignIn.signOut();
    

    This will sign the user out of both Firebase and Google.

Note that you’ll need to handle errors and exceptions appropriately in your own code, and you may also want to provide UI elements for users to sign in with Google.

Authenticate users with facebook

Here’s how to integrate Firebase Auth Flutter into your Flutter app so that users may log in with their Facebook credentials:

  1. Add the following packages to your pubspec.yaml file:
    dependencies:
      firebase_auth: ^3.1.0
      flutter_facebook_auth: ^3.5.0
    
  2. Initialize Firebase in your Flutter app:
    import 'package:firebase_core/firebase_core.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    
  3. Create a FirebaseAuth instance and a FacebookAuth instance:
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
    
    final FirebaseAuth _auth = FirebaseAuth.instance;
    final FacebookAuth facebookAuth = FacebookAuth.instance;
    
  4. To sign in with Facebook, call the login method on the FacebookAuth instance:
    try {
      final LoginResult result = await facebookAuth.login();
      final AccessToken accessToken = result.accessToken;
      final AuthCredential credential = FacebookAuthProvider.credential(accessToken.token);
      final UserCredential userCredential = await _auth.signInWithCredential(credential);
      final User user = userCredential.user;
      // TODO: Navigate to home screen or perform other actions with the user information
    } catch (e) {
      print(e);
    }
    

    The user will be prompted to log in with Facebook and give your app permission to view their email address after entering this code. Users can log in to Firebase with their Facebook credentials once your app has been authorized.

  5. To sign out, call the logOut method on the FacebookAuth instance:
    await facebookAuth.logOut();
    

    This will sign the user out of both Firebase and Facebook.

Keep in mind that you’ll need to write error and exception handling code and that you might wish to add Facebook sign-in UI components.

Conclusion

When it comes to securing your Flutter app’s user base, Firebase auth in Flutter is a great tool. It works smoothly with other Firebase services and provides a safe, scalable, and user-friendly method of handling user authentication.

You can integrate user signup, login, password reset, and social login with major services like Google, Facebook, Twitter, and more with minimal effort using Firebase Authentication.

Firebase Authentication offers extensive configuration options in addition to its standard functionality, allowing you to tailor it to your app’s specific requirements. The UI, user characteristics, and even authentication providers may all be modified to better suit your needs.

Generally speaking, Firebase Authentication is a helpful tool for any Flutter developer that wants to implement user authentication in their app. It provides a simple, secure authentication method that is well-documented.

Hello, I'm Cakra. I'm currently occupied with developing an application using the Flutter framework. Additionally, I'm also working on writing some articles related to it.

You May Also Like