Site icon AndroidVille

Flutter Firebase Authentication Tutorial

flutter firebase authentication

In this post on Flutter firebase authentication, we’ll take a look as to how we can authenticate users to our firebase app using firebase’s flutter plugin.

If you’re not familiar with flutter, I’d recommend reading this before going ahead. It’ll give you a basic idea about flutter and help you along with this tutorial.

http://ayusch.com/getting-started-with-flutter-app-development/

We’ll be creating a basic application with a login screen and a home page. It’ll have the ability to let the user Login and Logout of the application. We’ll also have the functionality to let the user register to our firebase app.

Here is the basic flow of the application:

 

So, let’s get started!

Create a Flutter Application

Go to Android Studio and create a Flutter application by clicking on New -> Flutter Project and following the wizard from there on.

Remove the code for default counter app and add the following lines:

import 'package:flutter/material.dart';
import 'package:flutter_firebase_auth/root_page.dart';
import 'LoginSignupPage.dart';
import 'authentication.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Authentication AndroidVille',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: RootPage(
        auth: new Auth(),
      ),
    );
  }
}

 

We’ll create the RootPage soon.

Note: Remember to NOT use AndroidX artifacts. Firebase’s plugin for flutter contains some annotations which are not supported in AndroidX. Until those are upgraded, let’s not use AndroidX.

Adding Dependencies

We’ll need to add some dependencies in android/flutter in order for flutter to use firebase authentication.

First, add this to your project level build.gradle file. For a flutter project, this is found in android/build.gradle

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

 

Next, we’ll need to apply google-services plugin to app level build.gradle. This is found in android/app/build.gradle. Add this line to the end of the file.

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

 

Finally, we’ll need to add firebase plugin for flutter. Open pubspec.yaml and add the following lines under dependencies:

firebase_auth: ^0.6.6

 

Creating Flutter Firebase Authentication service

Next up, we’ll need to create an authentication service for flutter’s firebase login system. This’ll be used by all the pages (or activities in android) to communicate with Firebase.

Create a new dart file named: authentication.dart

We’ll first add an abstract BaseAuth class that’d be implemented by our Auth class. This contains basic methods to login, signup, get user’s info and logout a user.

import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

abstract class BaseAuth {
  Future<String> signIn(String email, String password);
  Future<String> signUp(String email, String password);
  Future<FirebaseUser> getCurrentUser();
  Future<void> signOut();
}

 

In the same file, create a class named: Auth and implement the BaseAuth class. Override all the methods as shown below:

import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

abstract class BaseAuth {
  Future<String> signIn(String email, String password);
  Future<String> signUp(String email, String password);
  Future<FirebaseUser> getCurrentUser();
  Future<void> signOut();
}

class Auth implements BaseAuth {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  Future<String> signIn(String email, String password) async {
    FirebaseUser user = await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
    return user.uid;
  }

  Future<String> signUp(String email, String password) async {
    FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
    return user.uid;
  }

  Future<FirebaseUser> getCurrentUser() async {
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user;
  }

  Future<void> signOut() async {
    return _firebaseAuth.signOut();
  }
}

 

What we’re doing here is creating a global firebase instance and using it to perform login/logout for a user.

 

Creating a Root Page

We need to create a root to identify if the user is logged in or not. If the user is loggedin, we’ll direct him to home page else we’ll show him the login/registration screen.

Create a root_page.dart as shown below:

import 'package:flutter/material.dart';
import 'authentication.dart';
import 'LoginSignupPage.dart';
import 'home_page.dart';

class RootPage extends StatefulWidget {
  RootPage({this.auth});

  final BaseAuth auth;

  @override
  State<StatefulWidget> createState() => new _RootPageState();
}

enum AuthStatus {
  NOT_DETERMINED,
  LOGGED_OUT,
  LOGGED_IN,
}

class _RootPageState extends State<RootPage> {
  AuthStatus authStatus = AuthStatus.NOT_DETERMINED;
  String _userId = "";

  @override
  void initState() {
    super.initState();
    widget.auth.getCurrentUser().then((user) {
      setState(() {
        if (user != null) {
          _userId = user?.uid;
        }
        authStatus =
            user?.uid == null ? AuthStatus.LOGGED_OUT : AuthStatus.LOGGED_IN;
      });
    });
  }

  void _onLoggedIn() {
    widget.auth.getCurrentUser().then((user) {
      setState(() {
        _userId = user.uid.toString();
      });
    });
    setState(() {
      authStatus = AuthStatus.LOGGED_IN;
    });
  }

  void _onSignedOut() {
    setState(() {
      authStatus = AuthStatus.LOGGED_OUT;
      _userId = "";
    });
  }

  Widget progressScreenWidget() {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    switch (authStatus) {
      case AuthStatus.NOT_DETERMINED:
        return progressScreenWidget();
        break;
      case AuthStatus.LOGGED_OUT:
        return new LoginSignupPage(
          auth: widget.auth,
          onSignedIn: _onLoggedIn,
        );
        break;
      case AuthStatus.LOGGED_IN:
        if (_userId.length > 0 && _userId != null) {
          return new HomePage(
            userId: _userId,
            auth: widget.auth,
            onSignedOut: _onSignedOut,
          );
        } else
          return progressScreenWidget();
        break;
      default:
        return progressScreenWidget();
    }
  }
}

 

Main thing to notice here is the build method. For different states of user, we return different widgets. We’ll be creating the LoginSignupPage and HomePage soon.

For showing progress bar, we use the default CircularProgressIndicator provided by Flutter.

Also, notice that we pass the auth object in the constructor. This is passed on from main.dart

 

Creating the LoginSignupPage

This is the most important part, we’ll be creating a login/registration form. We’ll be differentiating between those forms on the basis of a formMode.

We’ll have a total of 6 widgets:

  1. A field for email.
  2. Field for password.
  3. Login button
  4. A button to toggle between login and registration form.
  5. ProgressBar
  6. Error message widget.

Here’s the code for LoginSignupPage:

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

class LoginSignupPage extends StatefulWidget {
  LoginSignupPage({this.auth, this.onSignedIn});

  final BaseAuth auth;
  final VoidCallback onSignedIn;

  @override
  State<StatefulWidget> createState() => new _LoginSignupPageState();
}

enum FormMode { LOGIN, SIGNUP }

class _LoginSignupPageState extends State<LoginSignupPage> {
  final _formKey = new GlobalKey<FormState>();

  String _email;
  String _password;
  String _errorMessage = "";

  // this will be used to identify the form to show
  FormMode _formMode = FormMode.LOGIN;
  bool _isIos = false;
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Flutter login demo"),
      ),
      body: Column(
        children: <Widget>[
          formWidget(),
          loginButtonWidget(),
          secondaryButton(),
          errorWidget(),
          progressWidget()
        ],
      ),
    );
  }

  Widget progressWidget() {
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    }
    return Container(
      height: 0.0,
      width: 0.0,
    );
  }

  Widget formWidget() {
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          _emailWidget(),
          _passwordWidget(),
        ],
      ),
    );
  }

  Widget _emailWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0.0, 100.0, 0.0, 0.0),
      child: TextFormField(
        maxLines: 1,
        keyboardType: TextInputType.emailAddress,
        autofocus: false,
        decoration: new InputDecoration(
            hintText: 'Enter Email',
            icon: new Icon(
              Icons.mail,
              color: Colors.grey,
            )),
        validator: (value) => value.isEmpty ? 'Email cannot be empty' : null,
        onSaved: (value) => _email = value.trim(),
      ),
    );
  }

  Widget _passwordWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0.0, 15.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        decoration: new InputDecoration(
            hintText: 'Password',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        validator: (value) => value.isEmpty ? 'Password cannot be empty' : null,
        onSaved: (value) => _password = value.trim(),
      ),
    );
  }

  Widget loginButtonWidget() {
    return new Padding(
        padding: EdgeInsets.fromLTRB(0.0, 45.0, 0.0, 0.0),
        child: new MaterialButton(
          elevation: 5.0,
          minWidth: 200.0,
          height: 42.0,
          color: Colors.blue,
          child: _formMode == FormMode.LOGIN
              ? new Text('Login',
                  style: new TextStyle(fontSize: 20.0, color: Colors.white))
              : new Text('Create account',
                  style: new TextStyle(fontSize: 20.0, color: Colors.white)),
          onPressed: _validateAndSubmit,
        ));
  }

  Widget secondaryButton() {
    return new FlatButton(
      child: _formMode == FormMode.LOGIN
          ? new Text('Create an account',
              style: new TextStyle(fontSize: 18.0, fontWeight: FontWeight.w300))
          : new Text('Have an account? Sign in',
              style:
                  new TextStyle(fontSize: 18.0, fontWeight: FontWeight.w300)),
      onPressed: _formMode == FormMode.LOGIN ? showSignupForm : showLoginForm,
    );
  }

  void showSignupForm() {
    _formKey.currentState.reset();
    _errorMessage = "";
    setState(() {
      _formMode = FormMode.SIGNUP;
    });
  }

  void showLoginForm() {
    _formKey.currentState.reset();
    _errorMessage = "";
    setState(() {
      _formMode = FormMode.LOGIN;
    });
  }

  Widget errorWidget() {
    if (_errorMessage.length > 0 && _errorMessage != null) {
      return new Text(
        _errorMessage,
        style: TextStyle(
            fontSize: 13.0,
            color: Colors.red,
            height: 1.0,
            fontWeight: FontWeight.w300),
      );
    } else {
      return new Container(
        height: 0.0,
      );
    }
  }

  bool _validateAndSave() {
    final form = _formKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    }
    return false;
  }

  _validateAndSubmit() async {
    setState(() {
      _errorMessage = "";
      _isLoading = true;
    });
    if (_validateAndSave()) {
      String userId = "";
      try {
        if (_formMode == FormMode.LOGIN) {
          userId = await widget.auth.signIn(_email, _password);
        } else {
          userId = await widget.auth.signUp(_email, _password);
        }
        setState(() {
          _isLoading = false;
        });

        if (userId.length > 0 && userId != null) {
          widget.onSignedIn();
        }
      } catch (e) {
        setState(() {
          _isLoading = false;
          if (_isIos) {
            _errorMessage = e.details;
          } else
            _errorMessage = e.message;
        });
      }
    } else {
      setState(() {
        _isLoading = false;
      });
    }
  }
}

 

Notice the method validateAndSubmit(), this is called when one presses the login button. First, we set initial state for loading to be true and empty error. 

Again, I recommend checking out this article to know what setState method does.

After that, we validate the form, and then on the basis of the formMode, we either log the user in or sign him up. In either of these cases, we get the userId.

Finally we call the onSignedIn method on the widget. This method is a VoidCallback which is provided in the constructor of LoginSignupPage by the root page.

Eventually, root page calls it’s onLoggedIn method which sets the userId and eventually calls setState(). This causes a rebuild and we go to the home screen.

This completes our LoginSignupPage. Now, it’s time to add the functionality to logout, in our home page.

 

Creating the Home Page

To complete this Flutter firebase authentication tutorial, we’ll have to add the ability to logout. Logout simply means setting empty user id and redirecting to LoginSignupPage.

Here is the code for HomePage:

import 'package:flutter/material.dart';

import 'authentication.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key, this.auth, this.userId, this.onSignedOut})
      : super(key: key);

  final BaseAuth auth;
  final VoidCallback onSignedOut;
  final String userId;

  @override
  State<StatefulWidget> createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {

  _signOut() async {
    try {
      await widget.auth.signOut();
      widget.onSignedOut();
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Flutter login demo'),
        actions: <Widget>[
          new FlatButton(
              child: new Text('Logout',
                  style: new TextStyle(fontSize: 17.0, color: Colors.white)),
              onPressed: _signOut)
        ],
      ),
      body: Center(
        child: Text("hello"),
      ),
    );
  }
}

 

We keep the SignOut button in the app bar. When the user clicks that, we call the onSignedOut method provided by the root_page.

Root page simply sets the authState of the user to LoggedOut and userId to empty string.

This is how the final result looks like:

 

Conclusion

Hope you found this article useful. If you did, let me know in the comments section below, I’ll love to write more such conceptual articles.

You can find the entire code for this article at: https://github.com/Ayusch/Flutter-Firebase-Authentication

If you have any questions, let me know in the comments below and I’ll be happy to help you!

 

*Important*: Join the AndroidVille SLACK  workspace for mobile developers where people share their learnings about everything latest in Tech, especially in Android Development, RxJava, Kotlin, Flutter, and mobile development in general.

Click on this link to join the workspace. It’s absolutely free!

Like what you read? Don’t forget to share this post on FacebookWhatsapp, and LinkedIn.

You can follow me on LinkedInQuoraTwitter, and Instagram where I answer questions related to Mobile Development, especially Android and Flutter.

If you want to stay updated with all the latest articles, subscribe to the weekly newsletter by entering your email address in the form on the top right section of this page.

Exit mobile version