Guide to Integrating Firebase Authentication and Firestore Database in a Flutter App

Photo by Andrew Neel on Unsplash

Guide to Integrating Firebase Authentication and Firestore Database in a Flutter App

Firebase Authentication and Firestore Database allow you to manage user authentication and store app data in real-time. This guide walks you through setting up Firebase Authentication for user management and Firestore for managing your app's database.


Step 1: Prepare Firebase Project

1.1 Create and Set Up Firebase Project

  1. Go to Firebase Console.

  2. Click Add Project, enter your project name, and follow the prompts to create the project.

  3. Enable Google Analytics (optional), then click Create Project.

1.2 Register Your Flutter App

  1. In your Firebase project, click Add App and choose your app's platform:

    • For Android, provide the package name found in android/app/src/main/AndroidManifest.xml under package.

    • For iOS, provide the bundle identifier found in ios/Runner.xcodeproj/project.pbxproj.

  2. Download the platform-specific configuration files:

    • For Android: google-services.json

    • For iOS: GoogleService-Info.plist


Step 2: Configure Your Flutter App

2.1 Install FlutterFire CLI

Install the FlutterFire CLI for an easier setup:

dart pub global activate flutterfire_cli

2.2 Initialize Firebase

Navigate to your project directory and initialize Firebase:

flutterfire configure

Follow the prompts to set up Firebase for your Flutter app. The CLI automatically updates your project files.

2.3 Add Firebase Core Dependency

In pubspec.yaml, add:

dependencies:
  firebase_core: ^2.17.1 # Use the latest version

Run:

flutter pub get

2.4 Platform-Specific Configuration

  1. Android: Place google-services.json in android/app/ and apply the necessary changes:

    • Update android/build.gradle:

        dependencies {
            classpath 'com.google.gms:google-services:4.3.15'
        }
      
    • Update android/app/build.gradle:

        apply plugin: 'com.google.gms.google-services'
      
    • Set minSdkVersion to at least 21 in android/app/build.gradle.

  2. iOS: Place GoogleService-Info.plist in ios/Runner/ and ensure:

    • platform :ios, '12.0' is set in Podfile.

    • Run:

        cd ios
        pod install
        cd ..
      

Step 3: Integrate Firebase Authentication

3.1 Add Authentication Dependency

Add the following to pubspec.yaml:

dependencies:
  firebase_auth: ^4.7.3 # Use the latest version

Run:

flutter pub get

3.2 Set Up Authentication

Enable the desired authentication methods in Firebase Console:

  • Go to Authentication > Sign-in method and enable Email/Password, Google, or other methods.

3.3 Implement Authentication in Flutter

Example: Email/Password Sign-Up and Sign-In

import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // Sign Up
  Future<void> signUp(String email, String password) async {
    try {
      await _auth.createUserWithEmailAndPassword(email: email, password: password);
      print("User registered successfully");
    } catch (e) {
      print("Sign-up failed: $e");
    }
  }

  // Sign In
  Future<void> signIn(String email, String password) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
      print("User signed in successfully");
    } catch (e) {
      print("Sign-in failed: $e");
    }
  }
}

Step 4: Integrate Firestore Database

4.1 Add Firestore Dependency

In pubspec.yaml, add:

dependencies:
  cloud_firestore: ^4.10.0 # Use the latest version

Run:

flutter pub get

4.2 Set Up Firestore

In the Firebase Console, navigate to Firestore Database and click Create Database. Choose a mode:

  • Start in test mode: No restrictions initially.

  • Start in production mode: Strict security rules.

4.3 Implement Firestore in Flutter

Example: Add and Retrieve Data

import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseService {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  // Add Data
  Future<void> addUserData(String userId, String name, String email) async {
    try {
      await _firestore.collection('users').doc(userId).set({
        'name': name,
        'email': email,
        'timestamp': FieldValue.serverTimestamp(),
      });
      print("User data added successfully");
    } catch (e) {
      print("Failed to add user data: $e");
    }
  }

  // Retrieve Data
  Future<void> getUserData(String userId) async {
    try {
      DocumentSnapshot doc = await _firestore.collection('users').doc(userId).get();
      print("User Data: ${doc.data()}");
    } catch (e) {
      print("Failed to fetch user data: $e");
    }
  }
}

Step 5: Combine Authentication and Firestore

A typical flow is creating a user profile in Firestore upon successful sign-up. Here’s how:

void signUpAndCreateProfile(String email, String password, String name) async {
  final AuthService authService = AuthService();
  final DatabaseService databaseService = DatabaseService();

  try {
    await authService.signUp(email, password);
    User? user = FirebaseAuth.instance.currentUser;
    if (user != null) {
      await databaseService.addUserData(user.uid, name, email);
      print("User profile created successfully");
    }
  } catch (e) {
    print("Failed to sign up and create profile: $e");
  }
}

Step 6: Test Your Integration

  1. Run your app:

     flutter run
    
  2. Test Authentication:

    • Sign up or sign in and verify the user appears in Firebase Console > Authentication.
  3. Test Firestore:

    • Add and fetch data, then verify it appears in Firebase Console > Firestore Database.

Step 7: Secure Your Firebase Rules

  1. Go to Firestore Rules in Firebase Console.

  2. Modify rules to secure data access, e.g., restrict access to authenticated users:

     rules_version = '2';
     service cloud.firestore {
       match /databases/{database}/documents {
         match /users/{userId} {
           allow read, write: if request.auth != null && request.auth.uid == userId;
         }
       }
     }
    

Conclusion

Integrating Firebase Authentication and Firestore Database gives your app robust backend support for managing users and data. This guide ensures a seamless setup for authentication and database functionality. For advanced features like Google Sign-In, analytics, or push notifications, explore the FlutterFire Documentation.