Paramclasses Academy - Blog

Tutorials Details

←
Post 28 of 40
→

Firebase in Flutter: Authentication, Cloud Firestore and Storage

Firebase in Flutter: Authentication, Cloud Firestore and Storage

November 3, 2026

❖ Firebase in Flutter: Authentication, Cloud Firestore and Storage

❖ Welcome to Param Classes!

Welcome to another practical Flutter App Development tutorial at Param Classes!

In our previous tutorials, we learned how to connect Flutter with REST APIs, PHP, and MySQL. We also explored how to send GET, POST, PUT, and DELETE requests.

Now, let's learn another popular backend solution: Firebase.

Firebase is a platform from Google that provides backend services for mobile and web applications.

With Firebase, developers can add user login, registration, database storage, file uploads, and many other features without building every backend service from scratch.

In this tutorial, we will understand three important Firebase services:

  1. Firebase Authentication

  2. Cloud Firestore

  3. Firebase Storage

We will also learn how to connect Firebase with Flutter and create practical examples.

✦ 1. What Is Firebase?

Firebase is a Backend-as-a-Service (BaaS) platform provided by Google.

It offers different services that help developers build applications faster.

For example, suppose you want to create a Student Management App.

You need:

  • User Registration

  • User Login

  • Student Information Storage

  • Profile Image Upload

  • Secure User Access

Firebase provides services that can help you implement these features.

Important Firebase services include:

  • Firebase Authentication

  • Cloud Firestore

  • Realtime Database

  • Firebase Storage

  • Firebase Cloud Messaging

  • Firebase Analytics

  • Firebase Crashlytics

Official website:

https://firebase.google.com

✦ 2. What Is Firebase Authentication?

Firebase Authentication helps developers manage user authentication.

Authentication means verifying the identity of a user before allowing access to protected features.

For example, a mobile application may provide:

  • User Registration

  • Email and Password Login

  • Password Reset

  • Google Sign-In

  • Phone Number Authentication

Firebase handles many of the authentication processes, so developers do not need to build the entire login system themselves.

Example:

A student opens your application and enters an email address and password.

Flutter sends the authentication request to Firebase. Firebase verifies the credentials and returns the authentication result.

✦ 3. What Is Cloud Firestore?

Cloud Firestore is a NoSQL cloud database.

It stores data in documents and collections rather than traditional relational database tables.

For example, a student collection may contain documents like this:

{
  "name": "Rahul",
  "course": "Flutter",
  "mobile": "9876543210"
}

Firestore structure:

  • Collection: students

  • Document: student_001

  • Fields: name, course, mobile

Firestore supports real-time data synchronization and offline capabilities on supported platforms.

It is useful for applications that need cloud-based data storage.

Official documentation:

https://firebase.google.com/docs/firestore

✦ 4. What Is Firebase Storage?

Firebase Storage allows applications to upload and store user-generated files.

For example:

  • Profile Photos

  • Student Documents

  • Product Images

  • PDF Files

  • Videos

  • Other Application Files

Instead of storing large files directly inside a database document, developers can store the files in Firebase Storage and save their download references or URLs in Firestore.

Official documentation:

https://firebase.google.com/docs/storage

✦ 5. Create a Firebase Project

First, open the Firebase Console:

https://console.firebase.google.com

Follow these steps:

  1. Sign in using your Google account.

  2. Click Add Project.

  3. Enter a project name, such as flutter_student_app.

  4. Follow the setup instructions.

  5. Choose whether to enable Google Analytics.

  6. Create the Firebase project.

After creating the project, you can register your Flutter application.

✦ 6. Install FlutterFire CLI

FlutterFire CLI helps configure Firebase for Flutter applications.

First, install the Firebase CLI by following the official instructions:

https://firebase.google.com/docs/cli

Then activate FlutterFire CLI:

dart pub global activate flutterfire_cli

Make sure the Dart global executable directory is available in your system PATH.

Sign in to Firebase:

firebase login

Create a Flutter project if you have not already created one:

flutter create firebase_student_app

Move into the project folder:

cd firebase_student_app

Now configure Firebase:

flutterfire configure

Select your Firebase project and the platforms you want to support.

This command generates the Firebase configuration file:

lib/firebase_options.dart

Follow the prompts carefully. The generated configuration connects your Flutter project with the selected Firebase project.

Official setup guide:

https://firebase.google.com/docs/flutter/setup

✦ 7. Add Firebase Packages in Flutter

Now install the Firebase packages.

For core Firebase functionality:

flutter pub add firebase_core

For user authentication:

flutter pub add firebase_auth

For Cloud Firestore:

flutter pub add cloud_firestore

For Firebase Storage:

flutter pub add firebase_storage

These packages allow Flutter to communicate with Firebase services.

✦ 8. Initialize Firebase in Flutter

Open lib/main.dart.

Import the required packages:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

import 'firebase_options.dart';

Initialize Firebase before running your application:

void main() async {

  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(const MyApp());

}

Understanding the code:

  • WidgetsFlutterBinding.ensureInitialized() prepares Flutter for asynchronous initialization.

  • Firebase.initializeApp() connects the application with Firebase.

  • DefaultFirebaseOptions.currentPlatform selects the configuration for the current platform.

  • runApp() starts the Flutter application.

✦ 9. Enable Email and Password Authentication

Open Firebase Console.

Follow these steps:

  1. Select your Firebase project.

  2. Open Authentication.

  3. Select Sign-in method.

  4. Choose Email/Password.

  5. Enable the Email/Password provider.

  6. Save the changes.

Now your Firebase project can authenticate users using email and password.

✦ 10. Create User Registration in Flutter

Create a registration function using Firebase Authentication.

Example:

import 'package:firebase_auth/firebase_auth.dart';

Future<void> registerUser(
  String email,
  String password,
) async {

  try {

    UserCredential userCredential =
        await FirebaseAuth.instance
            .createUserWithEmailAndPassword(
      email: email,
      password: password,
    );

    print('Registration Successful');

    print(userCredential.user?.uid);

  } on FirebaseAuthException catch (e) {

    print('Registration Error: ${e.message}');

  }

}

Explanation:

  • FirebaseAuth.instance accesses Firebase Authentication.

  • createUserWithEmailAndPassword() creates a new account.

  • email contains the user's email address.

  • password contains the user's password.

  • userCredential.user?.uid returns the Firebase user ID when registration succeeds.

Firebase manages the account credentials. Do not save plain-text passwords in Firestore.

✦ 11. Create User Login in Flutter

After registration, users can log in using their email and password.

Example:

Future<void> loginUser(
  String email,
  String password,
) async {

  try {

    UserCredential userCredential =
        await FirebaseAuth.instance
            .signInWithEmailAndPassword(
      email: email,
      password: password,
    );

    print('Login Successful');

    print(userCredential.user?.email);

  } on FirebaseAuthException catch (e) {

    print('Login Error: ${e.message}');

  }

}

Explanation:

  • signInWithEmailAndPassword() verifies the user's login credentials.

  • If authentication succeeds, Firebase returns the user information.

  • If authentication fails, Firebase provides an authentication error.

✦ 12. Create a Logout Function

When users want to sign out, use:

Future<void> logoutUser() async {

  await FirebaseAuth.instance.signOut();

  print('User Logged Out');

}

This signs the current user out of Firebase Authentication.

✦ 13. Store Data in Cloud Firestore

Now let's learn how to store student information in Firestore.

Open Firebase Console.

  1. Select Firestore Database.

  2. Click Create Database.

  3. Choose the database location.

  4. Complete the setup.

  5. Configure secure Firestore rules before using the database in production.

Now add this function in Flutter:

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> addStudent() async {

  try {

    await FirebaseFirestore.instance
        .collection('students')
        .add({

      'name': 'Rahul',

      'course': 'Flutter',

      'mobile': '9876543210',

      'createdAt': FieldValue.serverTimestamp(),

    });

    print('Student Added Successfully');

  } catch (e) {

    print('Error: $e');

  }

}

Explanation:

  • FirebaseFirestore.instance accesses Firestore.

  • collection('students') selects the students collection.

  • add() creates a document with an automatically generated ID.

  • The map contains the student information.

✦ 14. Read Data from Cloud Firestore

To retrieve all student records:

Future<void> fetchStudents() async {

  try {

    QuerySnapshot snapshot =
        await FirebaseFirestore.instance
            .collection('students')
            .get();

    for (var doc in snapshot.docs) {

      print(doc.data());

    }

  } catch (e) {

    print('Fetch Error: $e');

  }

}

This function reads documents from the students collection.

Each document contains student information.

You can display this data using Flutter widgets such as ListView.builder.

✦ 15. Update Firestore Data

To update a student record, you need its document ID.

Example:

Future<void> updateStudent(String documentId) async {

  try {

    await FirebaseFirestore.instance
        .collection('students')
        .doc(documentId)
        .update({

      'course': 'Advanced Flutter',

    });

    print('Student Updated Successfully');

  } catch (e) {

    print('Update Error: $e');

  }

}

The update() method changes the specified fields without replacing the complete document.

✦ 16. Delete Firestore Data

To delete a student document:

Future<void> deleteStudent(String documentId) async {

  try {

    await FirebaseFirestore.instance
        .collection('students')
        .doc(documentId)
        .delete();

    print('Student Deleted Successfully');

  } catch (e) {

    print('Delete Error: $e');

  }

}

This removes the selected document from the students collection.

✦ 17. Upload Images Using Firebase Storage

Now let's understand how to upload images.

For example, suppose a student wants to upload a profile photo.

Install the image picker package:

flutter pub add image_picker

Also make sure Firebase Storage is configured in your Firebase project.

Create a function to upload an image:

import 'dart:io';

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

Future<String?> uploadImage() async {

  try {

    final picker = ImagePicker();

    final XFile? image = await picker.pickImage(
      source: ImageSource.gallery,
    );

    if (image == null) {
      return null;
    }

    File file = File(image.path);

    String fileName =
        DateTime.now().millisecondsSinceEpoch.toString();

    Reference reference =
        FirebaseStorage.instance
            .ref()
            .child('student_images')
            .child('$fileName.jpg');

    await reference.putFile(file);

    String downloadUrl =
        await reference.getDownloadURL();

    print(downloadUrl);

    return downloadUrl;

  } catch (e) {

    print('Upload Error: $e');

    return null;

  }

}

Understanding the code:

  1. ImagePicker() creates an image picker.

  2. pickImage() allows the user to select an image.

  3. File() accesses the selected image file.

  4. FirebaseStorage.instance.ref() creates a storage reference.

  5. putFile() uploads the image.

  6. getDownloadURL() returns the file's download URL.

You can save this URL inside the student's Firestore document.

Important: Configure the required platform permissions and secure Storage rules. For web applications, use an upload method appropriate for web rather than dart:io File.

✦ 18. Difference Between Firebase Authentication, Firestore and Storage

All three services have different responsibilities.

Firebase Service Purpose
Authentication User Login and Registration
Cloud Firestore Store structured application data
Firebase Storage Store images and files

For example, in a Student Management App:

  • Authentication manages student accounts.

  • Firestore stores student names, courses, and profile information.

  • Storage stores profile photographs and documents.

Together, these services help developers build applications with cloud-based backend functionality.

✦ 19. Important Firebase Security Rules

Firebase provides security rules to control access to database documents and uploaded files.

Never use open development rules in a production application.

For example, a basic Firestore rule can restrict access to authenticated users:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {

    match /students/{studentId} {

      allow read, write:
        if request.auth != null;

    }

  }
}

This is only a basic starting point. It allows any authenticated user to read and write all student documents in that collection.

For a real student application, create rules that verify which user owns each record and what operations that user is permitted to perform.

✦ 20. Common Mistakes Beginners Should Avoid

1. Forgetting Firebase Initialization

Always initialize Firebase before accessing Firebase services.

2. Incorrect Firebase Configuration

Run flutterfire configure and verify the generated configuration file.

3. Authentication Provider Not Enabled

Enable Email/Password in Firebase Authentication before testing registration.

4. Incorrect Firestore Rules

Check database rules if reading or writing operations fail.

5. Storage Upload Errors

Check Firebase Storage setup, file permissions, and storage rules.

6. Ignoring Firebase Exceptions

Use try-catch to handle errors and display understandable messages.

7. Saving Passwords in Firestore

Use Firebase Authentication to manage passwords. Never store plain-text passwords in database documents.

✦ 21. Practical Assignment for Beginners

Now create a Firebase Student Management Application.

Your application should include:

  1. Student Registration Screen.

  2. Student Login Screen.

  3. Logout Button.

  4. Student Dashboard.

  5. Add Student Form.

  6. Student List using Cloud Firestore.

  7. Edit Student Details.

  8. Delete Student Record.

  9. Profile Image Upload using Firebase Storage.

  10. Store the Image URL in Firestore.

Try to complete this project step by step.

This assignment will help you understand how authentication, cloud database storage, and file uploads work together.

❖ Conclusion

Firebase is a useful backend platform for Flutter developers.

In this tutorial, we learned how to configure Firebase, initialize it in Flutter, create user accounts, log in, store information in Cloud Firestore, and upload images using Firebase Storage.

These services can help developers build applications with authentication and cloud-based data storage.

At Param Classes, we focus on practical programming tutorials that help beginners understand real-world application development.

Keep practicing Firebase integration and try building your own Student Management Application.

Keep Learning, Keep Building with Param Classes!

←
Post 28 of 40
→