Skip to content

Firebase Setup

Configure your own Firebase project to enable cloud backup, authentication, and other backend features in your rebranded app.

  • Firebase account (free tier available)
  • Your app’s new package name/bundle identifier
  • Admin access to configure Firebase services
  1. Go to Firebase Console
  2. Click “Create a project”
  3. Enter project name (e.g., “your-app-name”)
  4. Enable/disable Google Analytics (recommended: enable)
  5. Accept terms and create project

Recommended Settings:

  • Region: Choose closest to your target users
  • Analytics: Enable for user insights
  • Budget Alerts: Set up billing alerts
  1. In Firebase Console, go to Authentication
  2. Click “Get started”
  3. Enable sign-in methods:
    • Email/Password: For user accounts
    • Anonymous: For temporary accounts (optional)

Step 3: Automated Firebase Configuration with FlutterFire

Section titled “Step 3: Automated Firebase Configuration with FlutterFire”

The easiest way to configure Firebase for your Flutter app is using the FlutterFire CLI tool. This automates the entire setup process.

Terminal window
# Install Firebase CLI (prerequisite)
npm install -g firebase-tools
# Login to Firebase
firebase login
# Install FlutterFire CLI
dart pub global activate flutterfire_cli

Navigate to your Flutter project root and run:

Terminal window
# Configure Firebase for your project
flutterfire configure
# Follow the interactive prompts:
# 1. Select your Firebase project (or create new one)
# 2. Choose platforms: Android, iOS
# 3. Enter your package name: com.yourcompany.yourapp
# 4. Enter iOS bundle ID: com.yourcompany.yourapp

Example FlutterFire Configure Session:

$ flutterfire configure
i Found 2 Firebase projects.
? Select a Firebase project to configure your Flutter application with: your-app-project
? Which platforms should your configuration support (use arrow keys & space to select)? android, ios
i Firebase android app com.yourcompany.yourapp is not registered on Firebase project your-app-project.
i Registered a new Firebase android app on Firebase project your-app-project.
i Firebase ios app com.yourcompany.yourapp is not registered on Firebase project your-app-project.
i Registered a new Firebase ios app on Firebase project your-app-project.
Firebase configuration file lib/firebase_options.dart generated successfully with the following Firebase apps:
Platform Firebase App Id
android 1:123456789:android:abcdef123456
ios 1:123456789:ios:abcdef123456
Learn more about using this file and next steps from the documentation:
> https://firebase.google.com/docs/flutter/setup

The command automatically:

  • Creates Firebase apps for Android and iOS in your project
  • Downloads configuration files:
    • android/app/google-services.json for Android
    • ios/Runner/GoogleService-Info.plist for iOS
  • Generates lib/firebase_options.dart with platform-specific configuration
  • Updates your project with necessary Firebase dependencies

Check that these files were created:

your-app/
├── lib/
│ └── firebase_options.dart # ✓ Generated
├── android/app/
│ └── google-services.json # ✓ Downloaded
└── ios/Runner/
└── GoogleService-Info.plist # ✓ Downloaded

Add Firebase Authentication to your pubspec.yaml:

dependencies:
flutter:
sdk: flutter
# Firebase dependencies
firebase_core: ^2.24.2
firebase_auth: ^4.15.3
# Your existing dependencies...

Then run:

Terminal window
flutter pub get

Update your lib/main.dart:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart'; // Generated by FlutterFire
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize Firebase
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Your App Name',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}

Create a simple test to verify Firebase is working:

lib/services/firebase_test_service.dart
import 'package:firebase_auth/firebase_auth.dart';
class FirebaseTestService {
static Future<bool> testConnection() async {
try {
// Try to get current user (will be null if not signed in)
final user = FirebaseAuth.instance.currentUser;
print('Firebase connected successfully. Current user: ${user?.uid ?? 'None'}');
return true;
} catch (e) {
print('Firebase connection failed: $e');
return false;
}
}
}

Add this test to your main widget:

// In your main widget's initState or build method
@override
void initState() {
super.initState();
FirebaseTestService.testConnection();
}

If you need different Firebase projects for development/production:

Terminal window
# Configure for development
flutterfire configure --project=your-app-dev
# Configure for production
flutterfire configure --project=your-app-prod

Issue: Command not found

Terminal window
# Solution: Ensure Flutter pub global is in PATH
export PATH="$PATH":"$HOME/.pub-cache/bin"
# Or restart terminal after installation

Issue: Project not found

Terminal window
# Solution: Ensure you're logged into correct Firebase account
firebase logout
firebase login

Issue: Permission denied

Terminal window
# Solution: Check Firebase project permissions
# Ensure you have Editor or Owner role in Firebase Console

Issue: Configuration overwrites existing files

Terminal window
# Solution: Backup existing files before running configure
cp android/app/google-services.json android/app/google-services.json.backup
cp ios/Runner/GoogleService-Info.plist ios/Runner/GoogleService-Info.plist.backup

Step 4: Manual Configuration (Alternative to FlutterFire)

Section titled “Step 4: Manual Configuration (Alternative to FlutterFire)”

If you prefer manual configuration or FlutterFire configure doesn’t work for your setup, you can manually configure Firebase:

  1. In Firebase Console, go to Project Overview
  2. Click Android icon to add Android app
  3. Enter package name: com.yourcompany.yourapp
  4. Download google-services.json
  5. Place in android/app/google-services.json
  1. In Firebase Console, click iOS icon to add iOS app
  2. Enter bundle ID: com.yourcompany.yourapp
  3. Download GoogleService-Info.plist
  4. Add to ios/Runner/GoogleService-Info.plist via Xcode

Ensure your android/app/build.gradle.kts has the Google services plugin (it should already be configured):

plugins {
id("com.android.application")
id("com.google.gms.google-services") // This line
id("kotlin-android")
id("dev.flutter.flutter-gradle-plugin")
}
lib/core/constants/firebase_constants.dart
class FirebaseConstants {
// Authentication configuration
static const String projectId = 'your-project-id';
// Auth settings
static const bool enableAnonymousAuth = true;
static const bool enableEmailAuth = true;
// App-specific settings
static const String appName = 'Your App Name';
static const String supportEmail = 'support@yourcompany.com';
}
lib/features/auth/services/firebase_auth_service.dart
import 'package:firebase_auth/firebase_auth.dart';
class FirebaseAuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Get current user
User? get currentUser => _auth.currentUser;
// Listen to auth state changes
Stream<User?> get authStateChanges => _auth.authStateChanges();
// Sign in anonymously
Future<UserCredential?> signInAnonymously() async {
try {
return await _auth.signInAnonymously();
} catch (e) {
print('Anonymous sign in failed: $e');
return null;
}
}
// Sign in with email and password
Future<UserCredential?> signInWithEmailAndPassword({
required String email,
required String password,
}) async {
try {
return await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
} catch (e) {
print('Email sign in failed: $e');
return null;
}
}
// Create user with email and password
Future<UserCredential?> createUserWithEmailAndPassword({
required String email,
required String password,
}) async {
try {
return await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
} catch (e) {
print('User creation failed: $e');
return null;
}
}
// Sign out
Future<void> signOut() async {
try {
await _auth.signOut();
} catch (e) {
print('Sign out failed: $e');
}
}
// Delete current user
Future<void> deleteUser() async {
try {
await currentUser?.delete();
} catch (e) {
print('User deletion failed: $e');
}
}
}
lib/services/firebase_test_service.dart
import 'package:firebase_auth/firebase_auth.dart';
class FirebaseTestService {
static Future<bool> testAuthentication() async {
try {
// Test anonymous sign in
final credential = await FirebaseAuth.instance.signInAnonymously();
print('Anonymous sign in successful: ${credential.user?.uid}');
// Sign out
await FirebaseAuth.instance.signOut();
print('Sign out successful');
return true;
} catch (e) {
print('Authentication test failed: $e');
return false;
}
}
static Future<bool> testEmailAuth() async {
try {
const testEmail = 'test@example.com';
const testPassword = 'testpassword123';
// Create test user
final credential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: testEmail,
password: testPassword,
);
print('User created: ${credential.user?.uid}');
// Sign out and sign back in
await FirebaseAuth.instance.signOut();
final signInCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: testEmail,
password: testPassword,
);
print('Sign in successful: ${signInCredential.user?.uid}');
// Clean up - delete test user
await signInCredential.user?.delete();
print('Test user deleted');
return true;
} catch (e) {
print('Email authentication test failed: $e');
return false;
}
}
}
// In your main widget or test screen
ElevatedButton(
onPressed: () async {
final result = await FirebaseTestService.testAuthentication();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(result
? 'Firebase Auth working!'
: 'Firebase Auth failed'),
),
);
},
child: const Text('Test Firebase'),
),
Terminal window
# Test debug build
flutter run
# Test release build
flutter build apk --release
lib/core/config/environment.dart
abstract class Environment {
static const String firebaseProjectId = String.fromEnvironment(
'FIREBASE_PROJECT_ID',
defaultValue: 'your-project-id',
);
static const bool enableAnalytics = bool.fromEnvironment(
'ENABLE_ANALYTICS',
defaultValue: true,
);
static const bool enableAnonymousAuth = bool.fromEnvironment(
'ENABLE_ANONYMOUS_AUTH',
defaultValue: true,
);
}
Terminal window
# Debug build
flutter run --dart-define=FIREBASE_PROJECT_ID=your-project-id
# Release build
flutter build apk --release \
--dart-define=FIREBASE_PROJECT_ID=your-project-id \
--dart-define=ENABLE_ANALYTICS=true \
--dart-define=ENABLE_ANONYMOUS_AUTH=true

Problem: google-services.json not found

Terminal window
# Solution: Verify file location
ls android/app/google-services.json
# Should exist and contain your project configuration

Problem: iOS build fails with Firebase

Terminal window
# Solution: Clean and rebuild
cd ios
rm -rf build/
pod install --repo-update
cd ..
flutter clean
flutter build ios

Problem: FlutterFire configure fails

Terminal window
# Solution: Check Firebase CLI version and login status
firebase --version
firebase login --reauth
dart pub global activate flutterfire_cli

Problem: Sign-in fails in release builds

  • Verify SHA-1 certificate is added to Firebase (for Android)
  • Check package name/bundle ID matches exactly
  • Ensure configuration files are for the correct project
  • Test with debug builds first

Problem: Anonymous sign-in not working

  • Verify Anonymous authentication is enabled in Firebase Console
  • Check internet connectivity
  • Ensure Firebase is properly initialized

Problem: Firebase requests fail

  • Add network permissions to Android manifest (should already be present)
  • Check internet connectivity
  • Verify Firebase project is active and billing is set up
  • Use strong password requirements for email/password auth
  • Implement email verification for new accounts
  • Add rate limiting for sign-in attempts
  • Consider implementing multi-factor authentication
  • Use anonymous auth for guest users when appropriate
  • Restrict API keys to specific platforms in Firebase Console
  • Use different Firebase projects for debug/release if needed
  • Regularly rotate API keys
  • Monitor usage in Firebase Console
  • Never expose Firebase admin keys in client apps
  • Implement proper user data deletion
  • Respect user privacy preferences
  • Use secure connections (HTTPS) only
  • Follow GDPR/privacy law requirements

Add to pubspec.yaml:

dependencies:
firebase_performance: ^0.9.3

Initialize in main.dart:

import 'package:firebase_performance/firebase_performance.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Enable performance monitoring (optional)
FirebasePerformance.instance.setPerformanceCollectionEnabled(true);
runApp(MyApp());
}
import 'package:firebase_analytics/firebase_analytics.dart';
class AnalyticsService {
static final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
static Future<void> logUserSignIn(String method) async {
await _analytics.logLogin(loginMethod: method);
}
static Future<void> logUserSignUp(String method) async {
await _analytics.logSignUp(signUpMethod: method);
}
static Future<void> logCustomEvent(String eventName, Map<String, Object> parameters) async {
await _analytics.logEvent(
name: eventName,
parameters: parameters,
);
}
}

With Firebase configured:

  1. App Store Configuration - Prepare for distribution
  2. Testing Guide - Test all functionality
  3. Deployment - Build for production

Your app now has its own secure backend! ☁️