Firebase User Authentication in Flutter

Firebase User Authentication in Flutter

Flutter + Firebase Admin SDK: Adding Users; Updating Passwords. Each time you add a new user as the admin, you're logged out and the new user is logged in. Also, there is no way to update the user's password on the client.

Hello everyone, imagine that you have developed an enterprise-level Flutter application(client app) using firebase as the backend, and you are responsible for adding, updating and deleting users.

You will quickly realized that doing these from the client app has its limitations.

  • Each time you add a new user as the admin, you're logged out and the new user is logged in. You’ll then need to logout as the newly created user and re-login using your admin credentials; repeating this process to add a new user gets frustrating pretty quickly.
  • Also, there is no way to update the user’s password on the client

In this post, I will present to you with my solution for fixing these issue using the Firebase Admin SDK.

We’ll be writing some JavaScript, well Typescript, and deploying to Firebase. Don’t worry if you don’t know JavaScript/Typescript it’s quite similar to Dart and I will explain the code as we go along.

Firebase Config:

Ensure Email/Password Sign in is enabled in Firebase

Set Up a database structure like below

  • users: Once the user is registered they will show in this collection
  • users_registrations: when adding new users we submit to this collection if the user is successfully registered a document will be created in the “users” collection
  • user_update_password: whenever a document is added here it will trigger a cloud function to update the user's password
Code Time Flutter

This project uses firebase streams and the provider package to manage state; the moment a document is updated in Firestore it will be reflected on the client/Flutter app once the user has internet connection.

Also, the app has options for dark and light themes; 😀 see the post Flutter Light and Dark Theme to implement in your app.

We won't dive into the Flutter/Dart code in-depth because the focus is the firebase aspect, however, below are images of the folder structure and the final UI. You can get the full source code at Github Link

  • Folder Structure

Dark Theme


Light Theme

Code Time JavaScript/TypeScript

Ensure you have Node.js installed. Login to firebase using your credentials with the commands below:

npm install -g firebase-tools
npm install -g firebase-tools
firebase login
  • Create a new folder “firebase_credentials_cloud_functions”

Run the command, firebase init from that folder select functions at the prompt then select the corresponding project. Lastly, choose TypeScript as the language.

  • Create the folder structure below with the corresponding files.

  • onCreateUser.ts: whenever we add a users using our Flutter app to the collection “users_registrations” this function will fire and create the user using auth and add the document to ‘users’

  • onCreatePassword.ts: whenever we update a user’s password using our flutter app, a document will be written to the collection “users_update_password” this function will fire and update the user’s password.

  • Time to deploy our code: from the console/terminal run firebase deploy — only functions
We’re done!

Conclusion

Flutter and Firebase are the perfect duo for rapid mobile development; using both helps you the bring more value to your users while reducing lengthy configurations.

JavaScript/TypeScript is easy to learn/understand if you already know Dart.

Maybe in the future, Google will give us the ability to write cloud functions using dart. 😀

If this helped: please give me a clap, and star the GitHub repo, it keeps me motivated 😀

⭐ Source Code Flutter: GitHub Link

⭐ Source Code Firebase/JavaScript: GitHub Link

Firebase Authentication in Flutter

Firebase Authentication in Flutter

Firebase Authentication in Flutter - Production Patterns. This tutorial will cover the implementation and architecture for Firebase Authentication. We use Firebase Authentication in production to keep my code maintainable and easy to manage. We cover the basic login and sign up functionality.

Today we'll be going over the production practices I follow when implementing email authentication using Firebase in Flutter. We'll be building a social media app called compound. It's called compound because that's the middle word of the book in front of me on my desk. "The Compound Effect". Even if you don't want to build a social media app, I'll be teaching you the principles you need to apply to a firebase project to build literally any app you want.

The Architecture

If you don't know, I use an Mvvm Style architecture with Provider for my UI / Business logic separation and get_it as a service locator. I've found this to be the most consistent and easy to understand architecture that I've used in production. It keeps implementations short and specific. In short the architecture specifies that each view or basic widget can have it's own ViewModel that contains the logic specific to that piece of UI. The ViewModel will make use of services to achieve what the user is requesting through their interactions.

Services is where all the actual work happens. ViewModels make use of the services but doesn't contain any hard functionality outside of conditionals and calling services. So, to get to the task at hand. We'll have an Authentication service that we'll use to sign in or sign up with that will store an instance of the current firebase user for us to use when required. We will have two views, Login and SignUp view which will make of the two functions on the service. The entire backend of the application will be built using Firebase so make sure to go to your console and login with a gmail account.

Setup Firebase Project

Open up the firebase console and click on "Add Project". Call it "compound", go next, select your account and then create. This will take a few seconds to setup. When it's complete click on continue and you'll land on the overview page.

Click on the Android Icon (or iOS) and add your package name, I'll set mine to com.filledstacks.compound. I'll set the nickname to "Compound". Register the app and then download the google-services.json file. If you have your own project or want to use my starting code, which you can download here, open up the code and place the google-service.json file in the android/app folder. Then open the build.gradle file in the android/app folder and change the applicationId to match the one you entered for your Firebase project.

Setup in code

Open up the pubspec.yaml and add the firebase_auth plugin.

firebase_auth: ^0.15.3

Then we have to enable the google services. Open the build.gradle file in the android folder and add the google services dependency.

    dependencies {
        // existing dependencies
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // Add the google services classpath
        classpath 'com.google.gms:google-services:4.3.0'
    }

Open up the android/app/build.gradle file and apply the google services plugin. Add the following line at the bottom of the file.

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

That's it for the Android setup. Lets continue with the Firebase project. Once you've created the app you can go next and skip the firebase comms check that they do. On the left hand side, click on the Authentication Icon. The third icon from top (might change). Click on the Setup sign in methods button and click on email / password and enable it. That's it for the project setup, we'll get back to the Firebase console in the next episode.

Authentication Implementation

The starting code that I provided has a few things setup already.

  1. It contains the provider_architecture package which we use for the MvvmStyle bindings.
  2. It has an InputField widget which is styled how I want it.
  3. It has the locator for get_it setup like this
  4. It has a Navigation Service so we can navigate from the ViewModels and other services
  1. It has a Dialog Service for showing default dialogs
  1. It has the login view as well as the sign up view created and styled.

This is to make sure we keep the app to the point and only show the firebase parts. We'll be creating the Authentication service and then using it in the viewmodels, which are completely empty.

Authentication Service

The responsibility of the AuthenticationService in this case is to wrap the Firebase Authentication functionality for us. It will send the info we entered, and then tell us if it's successful or not. If it fails we return an error message to show the user. Under the services folder create a new file called authentication_service.dart.

import 'package:flutter/foundation.dart';

class AuthenticationService {
  Future loginWithEmail({@required String email, @required String password}) {
    // TODO: implement loginWithEmail
    return null;
  }

  Future signUpWithEmail({@required String email, @required String password}) {
    // TODO: implement signUpWithEmail
    return null;
  }
}

We'll start off keeping a reference to the FirebaseAuth instance locally. Then we'll perform signInWithEmailAndPassword and store the result in a variable called user. If there's no errors we'll check if the user is not null and return that value. If it fails we return the message from the error.

final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

Future loginWithEmail({
    @required String email,
    @required String password,
}) async {
    try {
        var user = await _firebaseAuth.signInWithEmailAndPassword(
            email: email, password: password);
        return user != null;
    } catch (e) {
        return e.message;
    }
}

Sign up looks very similar. The only difference is that the result of the createUserWithEmailAndPassword function returns a FirebaseAuth object instead of the user like login.

Future signUpWithEmail({
    @required String email,
    @required String password,
}) async {
    try {
        var authResult = await _firebaseAuth.createUserWithEmailAndPassword(
            email: email, password: password);
        return authResult.user != null;
    } catch (e) {
        return e.message;
    }
}

That's it for the AuthenticationService. Open up the locator.dart file and register the service as a lazy singleton. All that means is that there will only ever be 1 authentication service in existence, and we'll lazily create it once it has been requested the first time.4

void setupLocator() {
  locator.registerLazySingleton(() => NavigationService());
  locator.registerLazySingleton(() => DialogService());
  locator.registerLazySingleton(() => AuthenticationService());
}
Signup Logic

We'll start with sign up so that we can then perform a login afterwards. Open up the main.dart file and make sure home is set to SignUpView. Then open up the signup_view_model.dart file. We'll start by retrieving the AuthenticationService, NavigationService and DialogService from the locator. Then we'll create a function called SignUp that takes the email and password. In this function we'll set the view to busy before requesting, do the sign up. Then check the result, if it's a bool and it's true then we navigate to the HomeView. If it's false we'll show a general dialog, if it's a string we'll show the content as a dialog.

class SignUpViewModel extends BaseModel {
  final AuthenticationService _authenticationService =
      locator<AuthenticationService>();
  final DialogService _dialogService = locator<DialogService>();
  final NavigationService _navigationService = locator<NavigationService>();

  Future signUp({@required String email, @required String password}) async {
    setBusy(true);

    var result = await _authenticationService.signUpWithEmail(
        email: email, password: password);

    setBusy(false);
    if (result is bool) {
      if (result) {
        _navigationService.navigateTo(HomeViewRoute);
      } else {
        await _dialogService.showDialog(
          title: 'Sign Up Failure',
          description: 'General sign up failure. Please try again later',
        );

      }
    } else {
      await _dialogService.showDialog(
        title: 'Sign Up Failure',
        description: result,
      );
    }
  }
}

Open up the SignUpView file. Update the BusyButton to take in the busy property from the model and in the onPressed function call model.signUp.

 BusyButton(
    title: 'Sign Up',
    busy: model.busy,
    onPressed: () {
        model.signUp(
        email: emailController.text,
        password: passwordController.text,
        );
    },
)

If you run the app now, enter some details and login you'll see it navigate to the HomeView. If you want to see the error dialog enter a password with less than 6 characters and you'll see the dialog pop up. Also if you've already signed up you can try signing up with the same email again and you'll get a friendly error message :)

Login Logic

The login logic logic is literally exactly the same as the sign up logic. Being able to refactor for shared code is a good skill to have, I'll leave it up to you as an exercise to do. For now we'll write non dry code by simple repeating the pattern. Open up the login_view_model.dart

class LoginViewModel extends BaseModel {
  final AuthenticationService _authenticationService =
      locator<AuthenticationService>();
  final DialogService _dialogService = locator<DialogService>();
  final NavigationService _navigationService = locator<NavigationService>();

  Future login({@required String email, @required String password}) async {
    setBusy(true);

    var result = await _authenticationService.loginWithEmail(
        email: email, password: password);

    setBusy(false);

    if (result is bool) {
      if (result) {
        _navigationService.navigateTo(HomeViewRoute);
      } else {
        await _dialogService.showDialog(
          title: 'Login Failure',
          description: 'Couldn\'t login at this moment. Please try again later',
        );
      }
    } else {
      await _dialogService.showDialog(
        title: 'Login Failure',
        description: result,
      );
    }
  }
}

Open the login view. Pass the busy value to the BusyButton and in the onPressed function call the login function.

 BusyButton(
    title: 'Login',
    busy: model.busy,
    onPressed: () {
        model.login(
            email: emailController.text,
            password: passwordController.text,
        );
    },
)

Open up the main.dart file and change home to LoginView. If you re-run the code now you'll land on the LoginView. Enter the details you entered, click login and you're done :) . This is just the start of the app, we'll add functionalities a normal app would have throughout the rest of the series. In the next tutorial we'll make sure once we're signed in we go straight to the HomeView. We'll also create a user profile, make sure it's always available when the app is open and add roles (for later use ;) ).

I decided to ask you guys to start sharing the tutorials more, I'm still seeing some unmaintainable code when new clients come to me. We have to spread the architecture and code quality love around and make that the core focus when building apps. Until next time, Dane Mackier.

How to Create Liquid Swipe Animation in Flutter | Liquid Swipe Flutter

How to Create Liquid Swipe Animation in Flutter | Liquid Swipe Flutter

Today tutorial, I am going to show you how to create Liquid Swipe Animation in Flutter. liquid Swipe animation is amazing and its Created for iOS Platform and f

Today tutorial, I am going to show you how to create Liquid Swipe Animation in Flutter. liquid Swipe animation is amazing and its Created for iOS Platform and for React Native Platform. this animation Or Liquid Swipe Animation is Inspired by Cuberto.

Cuberto Liquid Swipe Animation

For this animation, we are will Need liquid_swipe Package. Liquid Swipe is the Unveils a New Page like Liquid Animation Just like the Above animation.

📱 What we're going to Build

How to Create Liquid Swipe Animation in Flutter

Let's Start the Tutorial

If you Don't know how to Create a Flutter app, check out Getting started with Flutter official tutorial.

Read More

11 Best Flutter Development Tools You Will Need As A Beginner | AllTechSavvy

11 Best Flutter Development Tools You Will Need As A Beginner | AllTechSavvy

In this tutorial, I am going to show you some of the Best Flutter development tools available in the market which will help you to make Development Produc

In this tutorial, I am going to show you some of the Best Flutter development tools available in the market which will help you to make Development Productivity Faster and Build Better Applications. Flutter is a Framework from google for Creating Cross-platform mobile apps.

Flutter is a Google UI Framework for Developers to Create Native applications for Mobile, Web, and Desktop Just in a Single Codebase. Flutter is Used by Millions of Developer Worldwide to create beautiful UI for their applications.we’ll look at some of the Best flutter development tools that can greatly improve your workflow and help you reduce development time.

Okay Without wasting any time. Let’s start in and Discover lots of New & awesome Flutter tools to develop your flutter apps like a legend.

Best Flutter Development Tool

#11. panache
Panache will help you to create beautiful themes for your flutter apps, you can customize colors & shapes in the apps.

Website: https://rxlabz.github.io/panache

#10.Codemagic
Codemagic is another awesome tool that’ll boost your flutter app development process. Cinemagic will test and release your flutter apps without issue & with no configuration. with the help Codemagic, you can automate the whole build process, test and release process of your flutter apps

Website: codemagic.io

#9.Appetize
Appetize is an Online web-based android Emulator and iOS simulator. Appetize will run Native mobile Apps in the browser with HTML and Javascript. which is easy to maintain and tacks.

Website: appetize.io

#8.TestMagic
TestMagic is a Free Companion app just like Codmagic for Fast & Easy testing of your android and iOS builds. Testmagics helps to distribute your builds and Testing android and Ios Apps on real devices as well as provide Feedback to your projects.

Website: testmagic.io

#7. Screenshots
A screenshot is a command-line utility for capturing Screenshots into the status bar placed in the device frame. Screenshots can be integrated into flutter to work transparently into Android and iOS.

Website: https://github.com/mmcc007/screenshots

#6.Supernova
Supernova Recently Introduced Support For Flutter Platform in Flutter interact. Supernova is a tool that helps you to Generate UI Code for Flutter. it’s support for material Design widgets a style manage that can bring the concepts of token and style into a flutter, you can have flutter app running side by side with Supernova and Change happen real-time.

Supernova will save your time by importing your Sketch Or Adobe Xd file, Select flutter as your export platform which will convert UI design into Production-ready Code.

Website: supernova.io

#5. Adobe Plugins For Flutter
Adobe Recently Released Plugins for Adobe Xd in Flutter Interact, which will Generate Code for Creating apps with flutter which is based on UI design in Adobe XD. this is Collaboration Between Google and Adobe that will be Expected to Released Early 2020. So Plugins will be Open Source According to Adobe.

Website: theblog.adobe.com

Read more