Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Using Firebase with Flutter: A Complete Guide

If you’re looking for the best Flutter app development company for your mobile application, then feel free to contact us at — support@flutterdevs.com.

Table of Contents:

Introduction

Why Use Firebase with Flutter?

Prerequisites

Steps to Follow

Setting Up Firebase Project

Setting Up Firebase in Your Flutter App

Firebase Authentication

Firestore Database

Firebase Storage

Firebase Functions (Optional)

Conclusion

References


Introduction

Firebase is an excellent backend service that allows you to add features such as user authentication, real-time databases, file storage, and serverless cloud functions to your Flutter apps. In this comprehensive guide, we will walk you through how to integrate Firebase with your Flutter app, covering Firebase Authentication, Firestore, Firebase Storage, and Firebase Functions.

Why Use Firebase with Flutter?

Firebase is one of the most popular backend-as-a-service platforms, and integrating it with Flutter can offer numerous benefits for developers. Firebase simplifies the process of adding complex features to your app while providing reliable and scalable backend services. Here’s why you should consider using Firebase with Flutter:

1. Fast and Easy Integration

Firebase offers a straightforward integration process for Flutter. With well-documented SDKs and a FlutterFire plugin (the official Flutter SDK for Firebase), Firebase enables you to quickly add backend services to your app, whether you’re building a simple app or a complex one. You don’t need to spend time setting up and maintaining your own backend servers.

  • FlutterFire SDK: The FlutterFire plugins are designed specifically for Flutter, making the integration between Firebase and Flutter seamless and developer-friendly.
  • Extensive Documentation: Firebase has excellent documentation and examples for Flutter, making it easier for developers to implement Firebase features.

2. Real-Time Database and Firestore

Firebase provides two main database solutions: Firebase Realtime Database and Cloud Firestore. Both are scalable, serverless databases that automatically sync data across all connected clients in real-time.

  • Cloud Firestore: It’s the next-generation database from Firebase, offering more advanced features, such as more powerful querying capabilities and a more flexible data structure.
  • Real-time Updates: Firebase automatically syncs data in real-time, making it ideal for apps that need live updates, such as social media apps, messaging apps, or live sports scores.

3. Authentication Made Easy

Firebase Authentication supports multiple authentication methods, including:

  • Email/Password Authentication (easy to set up)
  • Social Logins (Google, Facebook, Twitter, etc.)
  • Phone Authentication (SMS-based login)
  • Anonymous Authentication (to allow users to use your app without full login)

Firebase handles most of the complex security and user management tasks for you, including:

  • Password hashing
  • Session management
  • Security rules

This allows developers to focus more on building the app’s features and less on implementing authentication protocols.

4. Scalable and Secure Cloud Storage

Firebase provides Firebase Storage, a powerful service for storing user-generated content such as images, videos, and documents. Firebase Storage integrates seamlessly with Firebase Authentication, allowing you to control who has access to the files you store.

  • Automatic scaling: Firebase Storage is designed to scale automatically without requiring you to manage the infrastructure.
  • Security: Firebase Storage allows you to define access control rules, ensuring that users can only access files that they are authorized to view.
  • Integration with Firestore: You can easily store file URLs in Firestore and link them with other user data.

5. Serverless Backend with Firebase Functions

Firebase Functions allows you to write backend code that responds to events triggered by Firebase features or HTTPS requests without managing any server infrastructure. This is a huge benefit for developers who want to avoid setting up and maintaining their server-side code.

  • Event-driven Functions: Firebase Functions can respond to events from Firestore, Firebase Authentication, Firebase Realtime Database, and more.
  • Custom Logic: You can write custom server-side logic for tasks like sending notifications, processing payments, or triggering workflows.
  • Scaling Automatically: Firebase Functions scale automatically based on demand, which means they are perfect for apps that need to handle varying workloads.

6. Cloud Messaging

Firebase Cloud Messaging (FCM) allows you to send push notifications and messages to users, even when the app is in the background or closed. This is essential for user engagement in mobile applications, allowing you to send personalized updates, reminders, or promotional offers.

  • Push Notifications: Send targeted messages to specific user segments.
  • Cross-Platform: Firebase Cloud Messaging supports both Android and iOS, allowing you to send notifications to users on both platforms from a single API.

7. Analytics and Crash Reporting

Firebase provides Firebase Analytics, a powerful tool for tracking user interactions within your app. It helps you understand how users engage with your app, what features are most popular, and how users behave across different devices and platforms.

  • Firebase Crashlytics: Firebase also includes Crashlytics, a real-time crash reporting tool that helps you monitor and resolve issues in your app. With it, you can see exactly where the crash occurred and gather data on how many users were affected.
  • Real-Time Analytics: Firebase Analytics provides real-time insights into app usage, helping you make data-driven decisions to improve your app’s performance and user experience.

8. Easy Deployment and Hosting

Firebase Hosting allows you to deploy your web app (or even static assets like HTML, CSS, and JavaScript) to the cloud with a single command. It’s fast, secure, and scalable, making it perfect for Flutter web apps.

  • Global CDN: Firebase Hosting is backed by a content delivery network (CDN) that serves your content globally with low latency.
  • Simple Hosting: You can deploy static content with ease, and Firebase provides SSL by default, ensuring your content is served securely.

9. Pay As You Go Model

Firebase offers a pay-as-you-go model, which means you only pay for the services you use. The Firebase Free Tier offers generous limits, so you can get started with most features without incurring any costs. As your app scales and your user base grows, you can upgrade to a paid plan, which offers additional resources and greater capacity.

  • Scalable Pricing: Firebase’s pricing model is flexible, so you can scale as your app grows.
  • No Infrastructure Management: Since Firebase is fully managed, you don’t need to worry about maintaining servers, scaling infrastructure, or patching security issues.

10. Cross-Platform Compatibility

Firebase is designed to work seamlessly with both Android and iOS apps. The same Firebase project can be used across platforms, and the APIs are consistently designed, allowing you to focus on building cross-platform Flutter apps rather than worrying about platform-specific configurations.

  • Unified Platform: Firebase’s consistent APIs across Android, iOS, and Web mean you can build a truly cross-platform app.
  • FlutterFire Plugin: The official FlutterFire plugin provides easy access to Firebase services in Flutter, making it simple to integrate Firebase into your app.

Prerequisites

Before we dive into the tutorial, here’s what you need:

  1. Flutter SDK: Ensure you have Flutter installed on your machine. If not, follow the official Flutter installation guide: Install Flutter.
  2. Firebase Account: You’ll need a Firebase project. You can create one at Firebase Console.
  3. Android Studio/VS Code: You can use either Android Studio or VS Code for Flutter development.

Steps to Follow

Step 1: Set Up Firebase Project

Before integrating Firebase with your Flutter app, you need to create and configure a Firebase project.

1.1 Create a Firebase Project

  1. Visit the Firebase Console.
  2. Click on “Add Project” and follow the on-screen instructions.
  • Name your project.
  • Choose your country/region.
  • Disable or enable Google Analytics for your project.

2. Click “Create Project”.

1.2 Set Up Firebase Authentication

  1. In the Firebase Console, select Authentication from the sidebar.
  2. Go to the Sign-in method tab.
  3. Enable the authentication methods you want (Email/Password, Google, Facebook, etc.).
  • For this tutorial, we’ll enable Email/Password Authentication.

1.3 Set Up Firestore

  1. In the Firebase Console, click on Firestore Database in the sidebar.
  2. Choose Start in test mode (this is for testing, you can configure security rules later).
  3. Create your Firestore database in a specific location.

1.4 Set Up Firebase Storage

  1. In the Firebase Console, navigate to Storage and click on Get Started.
  2. Choose the storage location for your files.
  3. Set up security rules for storage, ensuring they fit your app’s privacy requirements.

Step 2: Set Up Firebase in Your Flutter App

2.1 Create a Flutter Project

If you haven’t already created a Flutter project, you can do so by running:

flutter create firebase_flutter_app
cd firebase_flutter_app

2.2 Add Firebase SDK to Your Flutter Project

In the Firebase Console, add your app to the Firebase project by selecting Add App and choosing Android or iOS.

Modify pubspec.yaml

Open the pubspec.yaml file and add the following Firebase dependencies:

dependencies:
flutter:
sdk: flutter
firebase_core: ^2.14.0 # Firebase core dependency
firebase_auth: ^4.5.0 # Firebase Authentication
cloud_firestore: ^5.0.0 # Firestore Database
firebase_storage: ^11.0.0 # Firebase Storage
firebase_functions: ^4.5.0 # Firebase Functions (optional)

After saving, run the following command to fetch the dependencies:

flutter pub get

Android Setup

  1. In the Firebase Console, click on Project settings > General.
  2. Click on the Add App button for Android and follow the setup instructions. Download the google-services.json file and add it to the android/app directory.

Modify android/build.gradle:

classpath 'com.google.gms:google-services:4.3.15' // Add this line in the dependencies section

In android/app/build.gradle:
apply plugin: 'com.google.gms.google-services' // Add this line at the bottom of the file

iOS Setup

  1. In the Firebase Console, click Add App for iOS and download the GoogleService-Info.plist file.
  2. Add this file to your ios/Runner directory.
  3. Run pod install in the ios directory to install necessary dependencies.

Step 3: Firebase Authentication

Firebase Authentication enables secure login and user management for your app.

3.1 Email/Password Authentication

Sign Up User

Here’s an example of how to allow users to sign up with their email and password:

import 'package:firebase_auth/firebase_auth.dart';

Future<User?> signUpWithEmailPassword(String email, String password) async {
try {
final UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
return userCredential.user; // Returns the user object
} catch (e) {
print("Error: $e");
return null;
}
}

Sign In User

Similarly, to sign in a user:

Future<User?> signInWithEmailPassword(String email, String password) async {
try {
final UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
return userCredential.user; // Returns the user object
} catch (e) {
print("Error: $e");
return null;
}
}

3.2 Google Sign-In (Optional)

For users who prefer to sign in using their Google accounts, you can use the google_sign_in package: Add google_sign_in Dependency

dependencies:
  google_sign_in: ^5.0.7

Sign In with Google

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

final GoogleSignIn googleSignIn = GoogleSignIn();

Future<User?> signInWithGoogle() async {
try {
GoogleSignInAccount? googleUser = await googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser!.authentication;

final OAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);

final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
return userCredential.user;
} catch (e) {
print("Error: $e");
return null;
}
}

Step 4: Firestore Database

Firestore is a NoSQL database that allows you to store and sync data in real-time.

4.1 Adding Data to Firestore

You can store data in Firestore by creating collections and documents.

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> addUserData(String name, String email) async {
try {
await FirebaseFirestore.instance.collection('users').add({
'name': name,
'email': email,
'createdAt': FieldValue.serverTimestamp(),
});
print('User added successfully');
} catch (e) {
print('Error: $e');
}
}

4.2 Fetching Data from Firestore

You can fetch data by querying Firestore collections.

Future<void> getUserData() async {
try {
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('users').get();
snapshot.docs.forEach((doc) {
print(doc['name']);
print(doc['email']);
});
} catch (e) {
print('Error: $e');
}
}

4.3 Listening for Real-time Updates

You can also listen to real-time changes in Firestore with snapshots():

StreamBuilder(
stream: FirebaseFirestore.instance.collection('users').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
var user = snapshot.data!.docs[index];
return ListTile(
title: Text(user['name']),
subtitle: Text(user['email']),
);
},
);
},
);

Step 5: Firebase Storage

Firebase Storage allows you to upload and retrieve files such as images, videos, and more.

5.1 Upload File to Firebase Storage

Here’s how to upload an image selected from the gallery:

import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

Future<void> uploadImageToStorage() async {
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.gallery);

if (image != null) {
try {
final ref = FirebaseStorage.instance.ref().child('images/${image.name}');
await ref.putFile(File(image.path)); // Uploading file
String imageUrl = await ref.getDownloadURL(); // Getting file URL
print('Image uploaded, URL: $imageUrl');
} catch (e) {
print("Error: $e");
}
}
}

5.2 Retrieve File from Firebase Storage

To retrieve the file, you can use the file URL:

Future<void> downloadImage(String imagePath) async {
try {
String downloadUrl = await FirebaseStorage.instance.ref(imagePath).getDownloadURL();
print('Download URL: $downloadUrl');
} catch (e) {
print('Error: $e');
}
}

Step 6: Firebase Functions (Optional)

Firebase Functions enable you to run backend code in response to Firebase events or HTTP requests. While this step is optional, it can help you build powerful features like sending emails or performing backend logic.

6.1 Setting Up Firebase Functions

To use Firebase Functions in your app:

  1. Install Firebase CLI and set up Firebase Functions in your project.
  2. Write a simple Firebase function to run when triggered.

6.2 Calling Firebase Functions from Flutter

import 'package:firebase_functions/firebase_functions.dart';

Future<void> callFirebaseFunction() async {
try {
final HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('yourFunctionName');
final response = await callable.call();
print(response.data);
} catch (e) {
print('Error calling function: $e');
}
}

Conclusion

You’ve now learned how to integrate Firebase with Flutter, covering the most important Firebase services such as Firebase Authentication, Firestore Database, Firebase Storage, and Firebase Functions. With Firebase, you can add powerful features to your Flutter apps without worrying about setting up your backend infrastructure.

As you continue developing with Flutter and Firebase, don’t forget to explore other Firebase services like Firebase Analytics, Firebase Cloud Messaging (FCM), and Firebase Crashlytics to further enhance your app’s capabilities.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


References:

Flutter – Realtime Database in Firebase – GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and…www.geeksforgeeks.org

A Complete Guide to Firebase Multifactor Authentication in Flutter | Codemagic Blog
A tutorial on how to use multifactor auth with Firebase authentication in Flutter.blog.codemagic.io


Feel free to connect with us:
 And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

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