Flutter firebase Auth Examples
Flutter firebase auth: How To Examples
Introduction
Firebase Authentication is a powerful service provided by Google that allows developers to easily add user authentication to their Flutter applications. It provides a secure and reliable way to handle user sign-up, sign-in, and password management.
In this tutorial, we will explore various examples of how to use the firebase_auth
package in Flutter, starting from the installation process.
Installation
To get started with firebase_auth
, you need to add the package as a dependency in your Flutter project. Open your project's pubspec.yaml
file and add the following line under the dependencies
section:
dependencies:
firebase_auth: ^3.0.0
Save the file and run the following command to fetch the package:
flutter pub get
Now you're ready to start using firebase_auth
in your Flutter application.
Example 1: Email and Password Authentication
In this example, we will demonstrate how to implement email and password authentication using firebase_auth
. We will cover the following steps:
- Initialize Firebase.
- Create a sign-up page.
- Create a sign-in page.
- Implement password reset functionality.
Step 1: Initialize Firebase
To use firebase_auth
, you need to initialize Firebase in your Flutter application. Follow these steps:
- Create a new project in the Firebase console (https://console.firebase.google.com).
- Add an Android app to your project and follow the instructions to download the
google-services.json
file. - Add an iOS app to your project and follow the instructions to download the
GoogleService-Info.plist
file. - Place the downloaded files in the respective folders of your Flutter project.
- Open your project's
android/app/build.gradle
file and add the following under thedependencies
section:
implementation platform('com.google.firebase:firebase-bom:28.4.0')
implementation 'com.google.firebase:firebase-auth'
- Open your project's
ios/Podfile
file and add the following under theuse_frameworks!
block:
pod 'Firebase/Auth'
- Run the following command to fetch the dependencies:
flutter pub get
cd ios && pod install && cd ..
- Import the
firebase_auth
package in your Dart file:
import 'package:firebase_auth/firebase_auth.dart';
Step 2: Create a Sign-up Page
To allow users to sign up with their email and password, follow these steps:
- Create a new Dart file, e.g.,
signup_page.dart
. - Import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
- Create a
TextEditingController
for the email and password fields:
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
- Build the sign-up page UI:
class SignUpPage extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Sign Up')),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: emailController,
decoration: InputDecoration(labelText: 'Email'),
),
TextField(
controller: passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
ElevatedButton(
onPressed: () {
signUpWithEmailAndPassword(
emailController.text,
passwordController.text,
);
},
child: Text('Sign Up'),
),
],
),
),
);
}
}
- Implement the
signUpWithEmailAndPassword
function:
void signUpWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
User? user = userCredential.user;
// Handle successful sign-up
} catch (e) {
// Handle sign-up failure
}
}
Step 3: Create a Sign-in Page
To allow users to sign in with their email and password, follow these steps:
- Create a new Dart file, e.g.,
signin_page.dart
. - Import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
- Create a
TextEditingController
for the email and password fields:
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
- Build the sign-in page UI:
class SignInPage extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Sign In')),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: emailController,
decoration: InputDecoration(labelText: 'Email'),
),
TextField(
controller: passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
ElevatedButton(
onPressed: () {
signInWithEmailAndPassword(
emailController.text,
passwordController.text,
);
},
child: Text('Sign In'),
),
],
),
),
);
}
}
- Implement the
signInWithEmailAndPassword
function:
void signInWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
User? user = userCredential.user;
// Handle successful sign-in
} catch (e) {
// Handle sign-in failure
}
}
Step 4: Implement Password Reset Functionality
To allow users to reset their passwords, follow these steps:
- Create a new Dart file, e.g.,
reset_password_page.dart
. - Import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
- Create a
TextEditingController
for the email field:
final TextEditingController emailController = TextEditingController();
- Build the reset password page UI:
class ResetPasswordPage extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Reset Password')),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: emailController,
decoration: InputDecoration(labelText: 'Email'),
),
ElevatedButton(
onPressed: () {
resetPassword(emailController.text);
},
child: Text('Reset Password'),
),
],
),
),
);
}
}
- Implement the
resetPassword
function:
void resetPassword(String email) async {
try {
await FirebaseAuth.instance.sendPasswordResetEmail(email: email);
// Handle successful password reset
} catch (e) {
// Handle password reset failure
}
}
Example 2: Google Sign-in
In this example, we will demonstrate how to implement Google Sign-in using firebase_auth
. We will cover the following steps:
- Configure Google Sign-in in Firebase console.
- Implement Google Sign-in in Flutter.
Step 1: Configure Google Sign-in in Firebase Console
To enable Google Sign-in for your Flutter application, follow these steps:
- Go to the Firebase console and open your project.
- Enable Google as a sign-in provider under the "Authentication" tab.
- Add your application's SHA-1 fingerprint to the Firebase project settings.
- Download the
google-services.json
file and place it in your project.
Step 2: Implement Google Sign-in in Flutter
To implement Google Sign-in in your Flutter application, follow these steps:
- Import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
- Create an instance of
GoogleSignIn
:
final GoogleSignIn googleSignIn = GoogleSignIn();
- Build the Google Sign-in button:
class GoogleSignInButton extends StatelessWidget {
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
signInWithGoogle();
},
child: Text('Sign In with Google'),
);
}
}
- Implement the
signInWithGoogle
function:
void signInWithGoogle() async {
try {
final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser!.authentication;
final OAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
UserCredential userCredential =
await FirebaseAuth.instance.signInWithCredential(credential);
User? user = userCredential.user;
// Handle successful sign-in
} catch (e) {
// Handle sign-in failure
}
}
Example 3: Anonymous Sign-in
In this example, we will demonstrate how to implement anonymous sign-in using firebase_auth
. We will cover the following steps:
- Implement anonymous sign-in in Flutter.
Step 1: Implement Anonymous Sign-in in Flutter
To implement anonymous sign-in in your Flutter application, follow these steps:
- Import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
- Build the anonymous sign-in button:
class AnonymousSignInButton extends StatelessWidget {
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
signInAnonymously();
},
child: Text('Sign In Anonymously'),
);
}
}
- Implement the
signInAnonymously
function:
void signInAnonymously() async {
try {
UserCredential userCredential =
await FirebaseAuth.instance.signInAnonymously();
User? user = userCredential.user;
// Handle successful sign-in
} catch (e) {
// Handle sign-in failure
}
}
Example 4: Sign Out
In this example, we will demonstrate how to implement sign-out functionality using firebase_auth
. We will cover the following steps:
- Implement sign-out functionality in Flutter.
Step 1: Implement Sign-out Functionality in Flutter
To implement sign-out functionality in your Flutter application, follow these steps:
- Import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
- Build the sign-out button:
class SignOutButton extends StatelessWidget {
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
signOut();
},
child: Text('Sign Out'),
);
}
}
- Implement the
signOut
function:
void signOut() async {
try {
await FirebaseAuth.instance.signOut();
// Handle successful sign-out
} catch (e) {
// Handle sign-out failure
}
}
Conclusion
In this tutorial, we explored various examples of how to use the firebase_auth
package in Flutter. We covered email and password authentication, Google Sign-in, anonymous sign-in, and sign-out functionality. By following these examples, you can easily implement user authentication in your Flutter applications using Firebase Authentication.