Android Core

Flutter Firebase Authentication Tutorial

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.

https://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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
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

1
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.

1
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:

1
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.

1
2
3
4
5
6
7
8
9
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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!

Published on Java Code Geeks with permission by Ayusch Jain, partner at our JCG program. See the original article here: Flutter Firebase Authentication Tutorial

Opinions expressed by Java Code Geeks contributors are their own.

Ayusch Jain

Ayusch is a Software Engineer currently working in Android Development. He's worked long enough that he's transformed into an Android himself :P. Additionally, he also maintains a community of Android developers called: AndroidVille and writes about Android on his website: https://ayusch.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Elena Gillbert
4 years ago

Hi….
I’m Elena gillbert.Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

Joshua
Joshua
4 years ago

please how do i add other fields for name and other details in the signup form

Back to top button