將 Firebase 新增至 Flutter 應用程式


事前準備

如果還沒有 Flutter 應用程式,可以完成「開始使用:試駕」來使用偏好的編輯器或 IDE 建立新的 Flutter 應用程式。

步驟 1:安裝必要的指令列工具

  1. 如果尚未安裝,請安裝 Firebase CLI

  2. 執行下列指令,使用 Google 帳戶登入 Firebase:

    firebase login
    
  3. 從任何目錄執行下列指令,安裝 FlutterFire CLI:

    dart pub global activate flutterfire_cli
    

步驟 2:將應用程式設為使用 Firebase

使用 FlutterFire CLI 設定 Flutter 應用程式,以便連結至 Firebase。

在 Flutter 專案目錄中執行下列指令,啟動應用程式設定工作流程:

flutterfire configure


步驟 3:在應用程式中初始化 Firebase

  1. 在 Flutter 專案目錄中執行下列指令,安裝核心外掛程式:

    flutter pub add firebase_core
    
  2. 在 Flutter 專案目錄中執行下列指令,確保 Flutter 應用程式的 Firebase 設定為最新版本:

    flutterfire configure
    
  3. lib/main.dart 檔案中,匯入 Firebase 核心外掛程式和您先前產生的設定檔:

    import 'package:firebase_core/firebase_core.dart';
    import 'firebase_options.dart';
    
  4. 同樣在 lib/main.dart 檔案中,使用設定檔匯出的 DefaultFirebaseOptions 物件初始化 Firebase:

    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    runApp(const MyApp());
    
  5. 重建 Flutter 應用程式:

    flutter run
    

如要使用示範專案,可以啟動 Firebase 模擬器,並在 lib/main.dart 檔案中使用 demoProjectId 初始化 Firebase (應以 demo- 開頭):

  await Firebase.initializeApp(
    demoProjectId: "demo-project-id",
  );

步驟 4:新增 Firebase 外掛程式

您可以在 Flutter 應用程式中透過各種 Firebase Flutter 外掛程式存取 Firebase,每個 Firebase 產品都有專屬外掛程式 (例如:Cloud FirestoreAuthenticationAnalytics 等)。

由於 Flutter 是跨平台架構,因此每個 Firebase 外掛程式都適用於 Apple、Android 和網頁平台。因此,如果您在 Flutter 應用程式中新增任何 Firebase 外掛程式,應用程式的 Apple、Android 和網頁版本都會使用該外掛程式。

新增 Firebase Flutter 外掛程式的方法如下:

  1. 在 Flutter 專案目錄中執行下列指令:

    flutter pub add PLUGIN_NAME
  2. 在 Flutter 專案目錄中執行下列指令:

    flutterfire configure
    

    執行這項指令可確保 Flutter 應用程式的 Firebase 設定為最新版本,並為 Android 上的 CrashlyticsPerformance Monitoring 應用程式新增必要的 Gradle 外掛程式。

  3. 完成後,請重建 Flutter 專案:

    flutter run
    

大功告成!您的 Flutter 應用程式已註冊並設定為使用 Firebase。

可用的外掛程式

產品 外掛程式名稱 iOS Android 網頁 其他 Apple 裝置
(macOS 等)
Windows
Firebase AI Logic 1 firebase_ai
Beta 版
Analytics firebase_analytics
Beta 版
App Check firebase_app_check
Beta 版
Authentication firebase_auth
Beta 版 Beta 版
Cloud Firestore cloud_firestore
Beta 版 Beta 版
Cloud Functions cloud_functions
Beta 版
Cloud Messaging firebase_messaging
Beta 版
Cloud Storage firebase_storage
Beta 版 Beta 版
Crashlytics firebase_crashlytics
Beta 版
Data Connect firebase_data_connect
Dynamic Links firebase_dynamic_links
In-App Messaging firebase_in_app_messaging
Firebase 安裝次數 firebase_app_installations
Beta 版
機器學習模型下載器 firebase_ml_model_downloader
Beta 版
Performance Monitoring firebase_performance
Realtime Database firebase_database
Beta 版
Remote Config firebase_remote_config
Beta 版

1 Firebase AI Logic 之前稱為「Vertex AI in Firebase」,外掛程式為 firebase_vertexai

試用 Analytics 提供的範例應用程式

與所有套件一樣,firebase_analytics 外掛程式隨附範例程式

  1. 開啟您已設定使用 Firebase 的 Flutter 應用程式 (請參閱本頁的操作說明)。

  2. 存取應用程式的 lib 目錄,然後刪除現有的 main.dart 檔案。

  3. Google Analytics 範例程式存放區,將下列兩個檔案複製並貼到應用程式的 lib 目錄中:

    • main.dart
    • tabs_page.dart
  4. 執行 Flutter 應用程式。

  5. 前往應用程式的 Firebase 專案 (位於 Firebase 控制台),然後按一下左側導覽列中的「Analytics」

    1. 按一下「資訊主頁」。如果 Analytics 運作正常,資訊主頁的「過去 30 分鐘內的活躍使用者人數」面板會顯示活躍使用者 (可能需要一段時間才能填入這個面板)。

    2. 按一下「DebugView」。啟用這項功能,即可查看範例程式產生的所有事件。

如要進一步瞭解如何設定 Analytics,請參閱 iOS+Android網頁的入門指南。

建構網路應用程式的注意事項

支援 Trusted Types

Firebase SDK for Flutter 支援使用 Trusted Types,有助於防範 DOM 型 (用戶端) XSS 攻擊。為應用程式啟用強制執行信任類型時,Firebase SDK 會使用自訂信任類型政策 (名為 flutterfire-firebase_coreflutterfire-firebase_auth 等) 將指令碼注入 DOM。

停用 Firebase JavaScript SDK 自動插入功能

根據預設,為網頁建構時,Firebase Flutter SDK 會自動插入 Firebase JavaScript SDK。如要避免系統自動插入 Firebase JavaScript SDK,請採取下列做法:

  1. 在 Flutter 專案的 web/index.html 檔案中,於 <script> 標記內新增下列屬性,即可忽略自動插入的指令碼:

    <!-- Add this property inside a <script> tag within your "web/index.html" file in your Flutter project -->
    <!-- Put in the names of all the plugins you wish to ignore: -->
    window.flutterfire_ignore_scripts = ['analytics', 'firestore'];
    
  2. 使用下列其中一種替代方案,手動載入指令碼:

    • window.addEventListener 回呼中,將 SDK 明確新增至 web/index.html 檔案:

        window.addEventListener('load', async function (ev) {
          window.firebase_firestore = await import("https://www.gstatic.com/firebasejs/12.6.0/firebase-firestore.js");
          window.firebase_analytics = await import("https://www.gstatic.com/firebasejs/12.6.0/firebase-analytics.js");
      
          _flutter.loader.loadEntrypoint().then(function (engineInitializer) {
            // rest of the code
      
    • 或者,從「gstatic」網域下載外掛程式的 Firebase JavaScript SDK 程式碼, 並將其儲存到 JavaScript 檔案,以便保留在專案中並手動載入:

        // "web/my-analytics.js" & "web/my-firestore.js" file loaded as a script into your "web/index.html" file: 
        window.addEventListener('load', async function (ev) {
          window.firebase_analytics = await import("./my-analytics.js");
          window.firebase_firestore = await import("./my-firestore.js");
      
          _flutter.loader.loadEntrypoint().then(function (engineInitializer) {
            // rest of the code
      

後續步驟