A starter helper for flutter developers wanting to use firebase phone authentication in their app.

Overview

riverpod_firebase_phone_auth

A new Flutter project template showing how to handle mobile authentication using Firebase and Riverpod.

Packages Used

  • Freezed - To generate union types that handle the various AuthStates
  • GoogleFonts - To use any font easily from fonts.google.com
  • responsive_sizer - For sizing purposes
  • flutter_typeahead - To implement the countries typeahead
  • country_list_pick - to flag assets and names for countries typeahead
  • firebase_core and firebase_auth

About

This project mainly uses freezed union types to implement the various states which most Login With Mobile applications use. If you don't know about freezed, go to the package freezed doc. The author has awesome docs, then find yourself a use case and keep freezing.

So when registering with phone, there are a couple of states where the register with phone could be in. - Initial e.g welcome screen - Page where the user enters the phone number. - Loading i.e prompting for SMS code/Checking if SMS CODE is valid - SmsCode has been sent to the users device i.e show code input screen - SMS has been validated. - SMS code is invalid. - Error - Some other error happened

What this template mainly does is handle these various states which could happen during mobile signup using union types and then maps the states into widgets.

The various authentication states

@freezed
class AuthState with _$AuthState {
/// Welcome page/User has not entered the phone number
const factory AuthState.initial() = _Initial;

/// When something is happening. 
const factory AuthState.loading(String msg) = _Loading;

/// when waiting for user to enter phone number
const factory AuthState.waitingForUserInput() = _WaitingForUserInput;

/// when the code has been sent to the user
const factory AuthState.codeSent(String verificationId) = _CodeSent;

/// when the user successfully signs in
const factory AuthState.gotFirebaseUser(
  User user,
) = _GotFirebaseUser;

/// if you're planning to intergrate an external backend with a custom user model
const factory AuthState.success(User firebaseUser, CustomUser user) =
    _Success;

/// when firebase SMS auto-retrieval times out
const factory AuthState.codeRetreivalTimedOut() = _CodeTimedOut;

/// when an error occurred during phone number verification.
const factory AuthState.verificationError(
  FirebaseAuthException firebaseAuthException, {
  String? verificationId,
  String? message,
}) = _VerificationError;

/// when an invalid-phone-number error occurs during phone number verification
const factory AuthState.invalidPhoneNumber(
  FirebaseAuthException firebaseAuthException,
  Function(String) retry,
  String message,
) = _InvalidPhoneNumber;
const factory AuthState.unknownError(Object error, StackTrace? stackTrace) =
    _UnknownError;
}

In our view, we then read the authentication state and map the various states to widgets which need to be shown depending on the state. No if statements, just pure functional transformation. Thanks to freezed

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final authState = watch(phoneVerificationStateProvider);
    final authStateNotifier = watch(phoneVerificationStateProvider.notifier);
    return authState.when(
      initial: () => WelcomePage(
        onAcceptButtonPressed: () {
          authStateNotifier.acceptToUsePhone;
        },
      ),
      loading: (msg) => LoadingWidget(msg: msg),
      waitingForUserInput: () => PhoneInputWidget(
        verifyFunction: (validatedPhone) {
          authStateNotifier.verifyPhoneNumber(validatedPhone);
        },
      ),
      codeSent: (verificationId) => SMSCodeInputWidget(
        onTap: (smsCode) {
          authStateNotifier.verifyCode(smsCode, verificationId);
        },
      ),
      gotFirebaseUser: (user) => whenAuthentcated(user),
      success: (firebaseUser, customUser) => whenAuthentcated(firebaseUser),
      codeRetreivalTimedOut: () => CodeRetrievalTimedOutWidget(
        onTryAgain: () => authStateNotifier.retry,
      ),
      verificationError: (_, verificationId, msg) => InvalidCodeWidget(
        verificationId: verificationId,
        invalidCodeMsg: msg,
        onEnterNewCode: () {
          if (verificationId != null) {
            authStateNotifier.reEnterVerificationCode(verificationId);
          }
        },
        onUseDifferentPhone: () => authStateNotifier.retry,
      ),
      invalidPhoneNumber: (_, retryFn, _) => InvalidPhoneNumberWidget(
        onChangePhoneNumber: () {
          authStateNotifier.retry;
        },
      ),
      unknownError: (error, stackTrace) => GenericErrorWidget(
        error: error,
        message: 'Unknown Error occured',
        retryWidget: ElevatedButton(
          onPressed: () {
            authStateNotifier.retry;
          },
          child: Container(
            child: const Text('Start again'),
            alignment: Alignment.center,
            width: Adaptive.w(40),
          ),
        ),
      ),
    );
  }

Steps to use the template

  1. Clone the repository and rename the package to what you want it called. flutter pub run change_app_package_name:main com.new.package.name
  2. run flutter create --org com.new.package.name
  3. Proceed to setup Firebase as per the instructions on FlutterFire
  4. Ensure phone authentication is enabled in firebase console for your project
  5. For android ensure you've enabled SafetyNet here
  6. Download the google-services.json file into android/app
  7. Run the app.

Issues

Known Issues

  • Not tested on iOS
  • Tests not written

Unknown Issues

If you encounter any issues running the example, feel free to open an issue.

You might also like...

A Flutter package to simplify firebase authentication.

firebase_authentication A Flutter package to simplify firebase authentication. Development State This is in a very, very early stage. It's a draft bas

Apr 24, 2022

Implementing Firebase Authentication with Riverpod following Flutter Domain Driven Development pattern

firebase_auth_flutter_ddd Firebase authentication example with Hooks Riverpod and Freezed following Flutter DDD architecture Getting Started This proj

Jan 8, 2023

Flutter Firebase CRUD Authentication.

flutterfire_samples A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you star

Nov 30, 2021

Firebase authentication 2021

firebase_authentication A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you

Oct 27, 2021

Implementation and architecture for Firebase Authentication

fluttercompoundapp A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you s

Nov 27, 2021

Starter app for Flutter that includes many different production app features; some not typically included in demo apps.

first_app: Starter app for a Flutter production app Maintainer: Greger Wedel, https://github.com/gregertw Listed on: Latest build and artifacts: ** La

Jan 8, 2023

A Flutter Starter Kit (Boilerplate) to kick-start your next Android and iOS app

A Flutter Starter Kit (Boilerplate) to kick-start your next Android and iOS app

Flutter Starter Kit (Boilerplate) using the BLoC Pattern A Flutter starter application that utilizes the BLoC Pattern. You can read more at this Mediu

Dec 28, 2022

Starter architectures for your next Flutter project in order to make it scalable and easy for maintenance and tests.

👷 🔧 🔩 Flutter Starter Architecture (MVVM) My custom starter project for Flutter apps. I was looking for a simple way to build Flutter app in a scal

Dec 25, 2022

A starter project guide to learn Flutter and its tools.

flutter_catalog A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Sep 21, 2021
Owner
Douglas Bett
Douglas Bett
Flutter ShopApp, you can see products and their prices, categories and their products, search for a product, add to favorite, add to cart, sign in and sign up.

shop_app_2 A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you started i

Muhammed Rezk Rajab 10 Aug 7, 2022
A cross platform application written in flutter to help people stick to their routines and achieve their goals

Scheduler Scheduler is a cross platform application written in flutter to help people stick to their routines and achieve their goals. Our service inc

Sidheshwar S 3 Jan 21, 2022
Use Firebase authentication with Flutter

user_login A skeleton futter project that use Firebase for user authentication. This project has be tested to run well on iOS, Android and WEB. I have

Dongjin Zou 0 Dec 26, 2021
Simple markdown editor. with custom keyboard helper for making bold, italic, list, URL, photoURL, etc

Flutter Markdown Editor A simple markdown creator/editor application, developer with flutter. special auxiliary keyboard features (for develop markdow

Ismael Shakverdiev 36 Dec 15, 2022
An App I made to learn of FIrebase Phone Auth and ML Kit

demoapp A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

D Srikhar Shashi 1 Oct 19, 2021
DoneIt is a sample note app 📝 Flutter application 📱 built to demonstrate use of Clean Architecture tools. Dedicated to all Flutter Developers with ❤️.

DoneIt ?? DoneIt is a sample note app ?? Flutter application ?? built to demonstrate use of Clean Architecture tools. Dedicated to all Flutter Develop

Shubham Chhimpa 175 Dec 24, 2022
Some built-in live templates support developers to use Flutter Riverpod faster on Intellij based

Flutter Riverpod live templates Flutter Riverpod live templates is a way to enhance the way you use Riverpod. It contains a collection of different sn

Minh Tran 27 Dec 16, 2022
Example how to use biometric authentication in flutter :alien:

# flutter_biometric_authentication A new Flutter project. ## Getting Started This project is a starting point for a Flutter application. A few res

Randald Villegas 2 Dec 31, 2021
Resturant FlutterApp withApi - A flutter app of a such restaurant with API and Firebase Authentication

Resturant_FlutterApp_withApi This is flutter app of a such restaurant with API a

null 32 Oct 5, 2022
Email and Password Authentication In Flutter & Firebase in Flutter 2.2

Email and Password Authentication In Flutter & Firebase in Flutter 2.2

BackSlash Flutter 43 Nov 23, 2022