Firebase Setup
Firebase Setup
Section titled “Firebase Setup”Configure your own Firebase project to enable cloud backup, authentication, and other backend features in your rebranded app.
Prerequisites
Section titled “Prerequisites”- Firebase account (free tier available)
- Your app’s new package name/bundle identifier
- Admin access to configure Firebase services
Step 1: Create Firebase Project
Section titled “Step 1: Create Firebase Project”1. Create New Project
Section titled “1. Create New Project”- Go to Firebase Console
- Click “Create a project”
- Enter project name (e.g., “your-app-name”)
- Enable/disable Google Analytics (recommended: enable)
- Accept terms and create project
2. Project Configuration
Section titled “2. Project Configuration”Recommended Settings:
- Region: Choose closest to your target users
- Analytics: Enable for user insights
- Budget Alerts: Set up billing alerts
Step 2: Enable Required Services
Section titled “Step 2: Enable Required Services”Authentication
Section titled “Authentication”- In Firebase Console, go to Authentication
- Click “Get started”
- 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.
1. Install FlutterFire CLI
Section titled “1. Install FlutterFire CLI”# Install Firebase CLI (prerequisite)npm install -g firebase-tools
# Login to Firebasefirebase login
# Install FlutterFire CLIdart pub global activate flutterfire_cli2. Run FlutterFire Configure
Section titled “2. Run FlutterFire Configure”Navigate to your Flutter project root and run:
# Configure Firebase for your projectflutterfire 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.yourappExample FlutterFire Configure Session:
$ flutterfire configurei 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, iosi 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 Idandroid 1:123456789:android:abcdef123456ios 1:123456789:ios:abcdef123456
Learn more about using this file and next steps from the documentation: > https://firebase.google.com/docs/flutter/setup3. What FlutterFire Configure Does
Section titled “3. What FlutterFire Configure Does”The command automatically:
- Creates Firebase apps for Android and iOS in your project
- Downloads configuration files:
android/app/google-services.jsonfor Androidios/Runner/GoogleService-Info.plistfor iOS
- Generates
lib/firebase_options.dartwith platform-specific configuration - Updates your project with necessary Firebase dependencies
4. Verify Generated Files
Section titled “4. Verify Generated Files”Check that these files were created:
your-app/├── lib/│ └── firebase_options.dart # ✓ Generated├── android/app/│ └── google-services.json # ✓ Downloaded└── ios/Runner/ └── GoogleService-Info.plist # ✓ Downloaded5. Update Dependencies
Section titled “5. Update Dependencies”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:
flutter pub get6. Initialize Firebase in Your App
Section titled “6. Initialize Firebase in Your App”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(), ); }}7. Test Firebase Connection
Section titled “7. Test Firebase Connection”Create a simple test to verify Firebase is working:
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@overridevoid initState() { super.initState(); FirebaseTestService.testConnection();}8. Reconfigure for Different Environments
Section titled “8. Reconfigure for Different Environments”If you need different Firebase projects for development/production:
# Configure for developmentflutterfire configure --project=your-app-dev
# Configure for productionflutterfire configure --project=your-app-prod9. Troubleshooting FlutterFire Configure
Section titled “9. Troubleshooting FlutterFire Configure”Issue: Command not found
# Solution: Ensure Flutter pub global is in PATHexport PATH="$PATH":"$HOME/.pub-cache/bin"# Or restart terminal after installationIssue: Project not found
# Solution: Ensure you're logged into correct Firebase accountfirebase logoutfirebase loginIssue: Permission denied
# Solution: Check Firebase project permissions# Ensure you have Editor or Owner role in Firebase ConsoleIssue: Configuration overwrites existing files
# Solution: Backup existing files before running configurecp android/app/google-services.json android/app/google-services.json.backupcp ios/Runner/GoogleService-Info.plist ios/Runner/GoogleService-Info.plist.backupStep 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:
Android Configuration
Section titled “Android Configuration”- In Firebase Console, go to Project Overview
- Click Android icon to add Android app
- Enter package name:
com.yourcompany.yourapp - Download
google-services.json - Place in
android/app/google-services.json
iOS Configuration
Section titled “iOS Configuration”- In Firebase Console, click iOS icon to add iOS app
- Enter bundle ID:
com.yourcompany.yourapp - Download
GoogleService-Info.plist - Add to
ios/Runner/GoogleService-Info.plistvia Xcode
Verify Manual Configuration
Section titled “Verify Manual Configuration”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")}Step 5: Update App Configuration
Section titled “Step 5: Update App Configuration”Update Firebase Configuration in Code
Section titled “Update Firebase Configuration in Code”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';}Update Authentication Service
Section titled “Update Authentication Service”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'); } }}Step 6: Test Firebase Integration
Section titled “Step 6: Test Firebase Integration”Authentication Test
Section titled “Authentication Test”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; } }}Add Test to Your App
Section titled “Add Test to Your App”// In your main widget or test screenElevatedButton( 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'),),Build and Test
Section titled “Build and Test”# Test debug buildflutter run
# Test release buildflutter build apk --releaseStep 7: Environment Configuration
Section titled “Step 7: Environment Configuration”Create Environment Files
Section titled “Create Environment Files”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, );}Build with Environment Variables
Section titled “Build with Environment Variables”# Debug buildflutter run --dart-define=FIREBASE_PROJECT_ID=your-project-id
# Release buildflutter build apk --release \ --dart-define=FIREBASE_PROJECT_ID=your-project-id \ --dart-define=ENABLE_ANALYTICS=true \ --dart-define=ENABLE_ANONYMOUS_AUTH=trueCommon Issues & Solutions
Section titled “Common Issues & Solutions”Configuration Issues
Section titled “Configuration Issues”Problem: google-services.json not found
# Solution: Verify file locationls android/app/google-services.json
# Should exist and contain your project configurationProblem: iOS build fails with Firebase
# Solution: Clean and rebuildcd iosrm -rf build/pod install --repo-updatecd ..flutter cleanflutter build iosProblem: FlutterFire configure fails
# Solution: Check Firebase CLI version and login statusfirebase --versionfirebase login --reauthdart pub global activate flutterfire_cliAuthentication Issues
Section titled “Authentication Issues”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
Network Issues
Section titled “Network Issues”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
Security Best Practices
Section titled “Security Best Practices”1. Authentication Security
Section titled “1. Authentication Security”- 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
2. API Keys and Configuration
Section titled “2. API Keys and Configuration”- 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
3. User Data Protection
Section titled “3. User Data Protection”- Implement proper user data deletion
- Respect user privacy preferences
- Use secure connections (HTTPS) only
- Follow GDPR/privacy law requirements
Optional: Analytics and Monitoring
Section titled “Optional: Analytics and Monitoring”Enable Performance Monitoring
Section titled “Enable Performance Monitoring”Add to pubspec.yaml:
dependencies: firebase_performance: ^0.9.3Initialize 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());}Analytics Events
Section titled “Analytics Events”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, ); }}Next Steps
Section titled “Next Steps”With Firebase configured:
- App Store Configuration - Prepare for distribution
- Testing Guide - Test all functionality
- Deployment - Build for production
Your app now has its own secure backend! ☁️