Implementing Email and Password Authentication in Flutter using Firebase | Flutter & Firebase
This is the beginning of Flutter and Firebase series. In this series, we’ll implement different Firebase services, one service at a time. For this article, we’ll see how to implement Firebase Authentication with email and password.
Let’s get started!
Prerequisites:
Installed Flutter and Dart SDK,
Android Studio / Visual Studio Code,
Able to run the default Flutter app.
Step 1: Setup Firebase Project and add dependencies
Follow the official Firebase documentation from here to setup Firebase in the project. Then, add the following in pubspec.yaml
—
dev_dependencies:
flutter_test:
sdk: flutter
firebase_core:
firebase_auth:
and do flutter packages get
Don’t forget to enable Email/Password Sign-in.
Firebase Console-> Authentication.
Step 2: Convert App to AndroidX
To make our app backward compatible, we need to enable androidX. To do so, follow the instructions here.
Step 3: Creating TextFormFields
and Button
We’ll reuse the following code for creating both Register
and Login
interface —
Scaffold(
body: Container(
padding: EdgeInsets.all(16),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
controller: emailTC,
decoration: InputDecoration(labelText: "Email")),
TextFormField(
controller: passwordTC,
obscureText: true,
decoration: InputDecoration(labelText: "Password"),
),
FlatButton(
child: Text("Submit"),
textColor: Colors.white,
color: Colors.blue,
onPressed: () {
doSomething(emailTC.text, passwordTC.text);
}),
],
)),
),
);
Step 3: Implementing Register functionality
We’ll create a function named register
to sign up users using email and password —
// Initializing Firebase Auth
final *FirebaseAuth* _auth = *FirebaseAuth*.instance;
// Defining Register function
register(emailAddr, pass) {
_auth.createUserWithEmailAndPassword(email: emailAddr, password: pass)
.then((FirebaseUser user) => print(user))
.catchError((e) => print(e));
}
Step 4: Implementing Login functionality
To implement login with email and password, we’ll create a login function —
// Initializing Firebase Auth
final *FirebaseAuth* _auth = *FirebaseAuth*.instance;
// Defining Login function
login(emailAddr, pass) {
_auth.signInWithEmailAndPassword(email: emailAddr, password: pass)
.then((FirebaseUser user) => print(user))
.catchError((e) => print(e));
}
You might get PlatformException (PlatformException(error, Given String is empty or null, null)
, to handle that we used .catchError()
method above. This can be referenced in this issue.
Well, that all!
If you followed every step properly, the code will work flawlessly unless the Flutter developers decide to change any method implemented here.
All the functionalities above are implemented in this repository.