Implementing Firebase Authentication in Flutter

Firebase provides a suite of hosted backend services, including authentication, real-time database, cloud storage, and machine learning. In this article, we’ll focus on Firebase Authentication and demonstrate how to integrate it into a Flutter application.

Project Setup

To get started, create a new Flutter project using the following command:

bash
flutter create firebase_auth_demo

Next, add the required dependencies to your pubspec.yaml file:

yml
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.10.0
firebase_auth: ^3.2.0

Setting up Firebase

Before you can use Firebase in your Flutter application, you need to create a Firebase project. Head over to the Firebase Console and follow the steps to create a new project.

Once you’ve created your project, you need to set up Firebase for each platform (Android, iOS, and web). Follow the configuration guides for each platform:

Initializing Firebase

Before you can use any Firebase service, you need to initialize the Firebase app. Add the following code to your main function:

“`dart
import ‘package:firebasecore/firebasecore.dart’;

void main() async {
await Firebase.initializeApp();
runApp(MyApp());
}
“`

Setting up Authentication

Create a new file called authentication_service.dart and add the following code:

“`dart
import ‘package:firebaseauth/firebaseauth.dart’;

class AuthenticationService {
final FirebaseAuth _firebaseAuth;

AuthenticationService(this._firebaseAuth);

Future signUp(String email, String password) async {
try {
await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
} catch (e) {
print(e.message);
}
}

Future signIn(String email, String password) async {
try {
await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
} catch (e) {
print(e.message);
}
}

Future signOut() async {
await _firebaseAuth.signOut();
}
}
“`

Building the UI

Create a new file called sign_up_screen.dart and add the following code:

“`dart
import ‘package:flutter/material.dart’;
import ‘package:firebaseauthdemo/authentication_service.dart’;

class SignUpScreen extends StatefulWidget {
@override
_SignUpScreenState createState() => _SignUpScreenState();
}

class _SignUpScreenState extends State {
final _formKey = GlobalKey();
String _email, _password;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Sign Up’),
),
body: Form(
key: formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
labelText: ‘Email’,
),
validator: (value) {
if (value.isEmpty) {
return ‘Please enter an email’;
}
return null;
},
onSaved: (value) => _email = value,
),
TextFormField(
decoration: InputDecoration(
labelText: ‘Password’,
),
obscureText: true,
validator: (value) {
if (value.isEmpty) {
return ‘Please enter a password’;
}
return null;
},
onSaved: (value) => _password = value,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (
formKey.currentState.validate()) {
formKey.currentState.save();
AuthenticationService(FirebaseAuth.instance).signUp(
email, _password);
}
},
child: Text(‘Sign Up’),
),
],
),
),
);
}
}
“`

Similarly, create a sign_in_screen.dart file and add the following code:

“`dart
import ‘package:flutter/material.dart’;
import ‘package:firebaseauthdemo/authentication_service.dart’;

class SignInScreen extends StatefulWidget {
@override
_SignInScreenState createState() => _SignInScreenState();
}

class _SignInScreenState extends State {
final _formKey = GlobalKey();
String _email, _password;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Sign In’),
),
body: Form(
key: formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
labelText: ‘Email’,
),
validator: (value) {
if (value.isEmpty) {
return ‘Please enter an email’;
}
return null;
},
onSaved: (value) => _email = value,
),
TextFormField(
decoration: InputDecoration(
labelText: ‘Password’,
),
obscureText: true,
validator: (value) {
if (value.isEmpty) {
return ‘Please enter a password’;
}
return null;
},
onSaved: (value) => _password = value,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (
formKey.currentState.validate()) {
formKey.currentState.save();
AuthenticationService(FirebaseAuth.instance).signIn(
email, _password);
}
},
child: Text(‘Sign In’),
),
],
),
),
);
}
}
“`

Finally, create a home_screen.dart file and add the following code:

“`dart
import ‘package:flutter/material.dart’;
import ‘package:firebaseauthdemo/authentication_service.dart’;

class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Home’),
),
body: Center(
child: ElevatedButton(
onPressed: () {
AuthenticationService(FirebaseAuth.instance).signOut();
},
child: Text(‘Sign Out’),
),
),
);
}
}
“`

That’s it! You’ve now implemented Firebase Authentication in your Flutter app.

Leave a Reply

Your email address will not be published. Required fields are marked *