返回博客
教程2025年4月20日安安科技团队阅读时间 12 分钟

FIREBASE +
FLUTTER 集成

逐步教你将 Firebase 集成到 Flutter 应用,轻松搭建后端服务。身份验证、Firestore、Cloud Storage 以及推送通知,一应俱全。

Firebase Flutter 集成
// 简报

Firebase 是 Google 提供的全方位后端即服务(BaaS)平台,让你无需自行搭建和维护服务器基础设施。凭借 Flutter 出色的 Firebase 集成能力,你可以在几分钟内为应用添加强大的后端功能,而不必花上几个月。

本指南将带你配置每个现代应用都需要的 Firebase 服务:用户身份验证、实时数据库、文件存储和推送通知。完成之后,你的 Flutter 应用就会拥有一个功能完备的后端。

步骤 1:Firebase 项目配置

首先,我们需要创建一个 Firebase 项目并为 Flutter 进行配置。这包括在 Firebase Console 中创建项目,以及安装所需的依赖包。

Firebase Console 配置:

  1. 1. 打开 console.firebase.google.com
  2. 2. 点击“创建项目”(Create a project)
  3. 3. 输入项目名称
  4. 4. 启用 Google Analytics(推荐开启)
  5. 5. 点击“创建项目”完成创建
terminal
# Add the Firebase packages you need — pub resolves
# the latest compatible versions automatically:
flutter pub add firebase_core firebase_auth \
  cloud_firestore firebase_storage firebase_messaging

# pubspec.yaml is updated for you; dependencies are
# fetched as part of the command (no manual pub get).

步骤 2:Firebase 身份验证

Firebase Auth 提供多种开箱即用的身份验证方式,包括邮箱/密码、Google 登录、Apple 登录等。下面我们来实现邮箱/密码验证。

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

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  
  // Get current user
  User? get currentUser => _auth.currentUser;
  
  // Auth state changes stream
  Stream<User?> get authStateChanges => _auth.authStateChanges();
  
  // Sign up with email and password
  Future<UserCredential?> signUpWithEmail(String email, String password) async {
    try {
      return await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
    } on FirebaseAuthException catch (e) {
      print('Sign up error: ${e.message}');
      return null;
    }
  }
  
  // Sign in with email and password
  Future<UserCredential?> signInWithEmail(String email, String password) async {
    try {
      return await _auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
    } on FirebaseAuthException catch (e) {
      print('Sign in error: ${e.message}');
      return null;
    }
  }
  
  // Sign out
  Future<void> signOut() async {
    await _auth.signOut();
  }
}

实用技巧:

  • 在 Firebase Console 中启用邮箱/密码验证
  • 使用 StreamBuilder 监听验证状态变化
  • 为所有验证方法实现完善的错误处理
  • 考虑添加邮箱验证以提升安全性

步骤 3:Cloud Firestore 数据库

Firestore 是一个 NoSQL 文档数据库,可以将数据实时同步到所有连接的设备。非常适合聊天应用、协作工具,以及任何需要实时更新的应用。

firestore_service.dart
import 'package:cloud_firestore/cloud_firestore.dart';

class FirestoreService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;
  
  // Create/Update document
  Future<void> createUser(String uid, Map<String, dynamic> userData) async {
    await _db.collection('users').doc(uid).set(userData);
  }
  
  // Read document
  Future<DocumentSnapshot> getUser(String uid) async {
    return await _db.collection('users').doc(uid).get();
  }
  
  // Read collection with real-time updates
  Stream<QuerySnapshot> getMessagesStream(String chatId) {
    return _db
        .collection('chats')
        .doc(chatId)
        .collection('messages')
        .orderBy('timestamp', descending: true)
        .snapshots();
  }
  
  // Add document to collection
  Future<DocumentReference> addMessage(String chatId, Map<String, dynamic> message) async {
    return await _db
        .collection('chats')
        .doc(chatId)
        .collection('messages')
        .add(message);
  }
  
  // Update document
  Future<void> updateUserProfile(String uid, Map<String, dynamic> updates) async {
    await _db.collection('users').doc(uid).update(updates);
  }
  
  // Delete document
  Future<void> deleteMessage(String chatId, String messageId) async {
    await _db
        .collection('chats')
        .doc(chatId)
        .collection('messages')
        .doc(messageId)
        .delete();
  }
}

Firestore 最佳实践:

  • 数据结构尽量保持扁平
  • 以子集合(subcollection)处理一对多关系
  • 为经常查询的字段建立索引
  • 多个操作请使用批量写入

步骤 4:Firebase Cloud Storage

Firebase Storage 负责处理文件的上传、下载和管理。非常适合存储用户头像、聊天图片、文档,以及应用需要存储的任何其他文件。

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

class StorageService {
  final FirebaseStorage _storage = FirebaseStorage.instance;
  
  // Upload file and get download URL
  Future<String?> uploadFile(File file, String path) async {
    try {
      final ref = _storage.ref().child(path);
      final uploadTask = ref.putFile(file);
      
      final snapshot = await uploadTask;
      final downloadURL = await snapshot.ref.getDownloadURL();
      
      return downloadURL;
    } catch (e) {
      print('Upload error: $e');
      return null;
    }
  }
  
  // Upload profile picture
  Future<String?> uploadProfilePicture(File image, String userId) async {
    final path = 'profile_pictures/$userId.jpg';
    return await uploadFile(image, path);
  }
  
  // Upload chat image
  Future<String?> uploadChatImage(File image, String chatId) async {
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final path = 'chat_images/$chatId/$timestamp.jpg';
    return await uploadFile(image, path);
  }
  
  // Delete file
  Future<void> deleteFile(String path) async {
    try {
      await _storage.ref().child(path).delete();
    } catch (e) {
      print('Delete error: $e');
    }
  }
  
  // Get download URL for existing file
  Future<String?> getDownloadURL(String path) async {
    try {
      return await _storage.ref().child(path).getDownloadURL();
    } catch (e) {
      print('Get URL error: $e');
      return null;
    }
  }
}

存储技巧:

  • 上传前先压缩图片以节省带宽
  • 使用具有描述性的文件路径,方便管理
  • 设置安全规则以保护用户文件
  • 可考虑使用 Cloud Functions 处理图片

步骤 5:推送通知

Firebase Cloud Messaging(FCM)让你可以向用户发送推送通知。无论是提升用户参与度、聊天通知,还是向用户传递最新信息,都不可或缺。

messaging_service.dart
import 'package:firebase_messaging/firebase_messaging.dart';

class MessagingService {
  final FirebaseMessaging _messaging = FirebaseMessaging.instance;
  
  // Initialize messaging
  Future<void> initialize() async {
    // Request permission
    NotificationSettings settings = await _messaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    
    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    }
    
    // Get FCM token
    String? token = await _messaging.getToken();
    print('FCM Token: $token');
    
    // Save token to Firestore for this user
    // await FirestoreService().updateUserToken(token);
  }
  
  // Handle foreground messages
  void handleForegroundMessages() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Received message: ${message.notification?.title}');
      
      // Show local notification or update UI
      _showLocalNotification(message);
    });
  }
  
  // Handle background message taps
  void handleBackgroundMessages() {
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('Message clicked: ${message.data}');
      
      // Navigate to specific screen based on message data
      _handleMessageNavigation(message.data);
    });
  }
  
  // Subscribe to topic
  Future<void> subscribeToTopic(String topic) async {
    await _messaging.subscribeToTopic(topic);
  }
  
  // Unsubscribe from topic
  Future<void> unsubscribeFromTopic(String topic) async {
    await _messaging.unsubscribeFromTopic(topic);
  }
  
  void _showLocalNotification(RemoteMessage message) {
    // Implement local notification display
  }
  
  void _handleMessageNavigation(Map<String, dynamic> data) {
    // Implement navigation logic based on message data
  }
}

通知最佳实践:

  • 发送通知前务必先获取用户许可
  • 使用主题(topic)向特定用户群组广播
  • 附上相关数据以支持深度链接(deep linking)
  • 在 iOS 和 Android 上都测试通知

把所有功能组合起来

完整的 Firebase 集成:

main.dart
// main.dart
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return HomeScreen();
          } else {
            return LoginScreen();
          }
        },
      ),
    );
  }
}

你已构建的功能

  • 用户身份验证系统
  • 实时数据库集成
  • 文件上传/下载功能
  • 推送通知系统
  • 可扩展的后端基础设施

下一步

  • 设置 Firebase 安全规则
  • 添加 Firebase Analytics
  • 实现 Cloud Functions
  • 添加崩溃报告
  • 为生产环境进行优化
// 后端

需要 Firebase 专家?

我们的团队开发过数以百计由 Firebase 驱动的 Flutter 应用。让我们帮你为应用打造稳健、可扩展的后端!

联系我们
// 信号扩散

分享这篇教程