Flutter 使用Firebase新建 app 專案,並針對不同 stage 做自動化腳本佈署

Sebastian Hsu
5 min readMar 1, 2023

--

每次做 Flutter 要連結 Firebase 的時候,都是按照記憶去 try,常常做過的忘記,又要再 Google 一次試錯,這次把它記錄下來,希望以後少走錯路。

要在 Flutter 使用 Firebase 的方法,使用CLI,所以不用到後臺新建 project喔。

安裝 Firebase CLI

參考這一篇安裝,只需要確定可以在 command line 執行 firebase 就好,下面它要你做的先不要管它。

新建 Firebase project

以下是參考 https://firebase.google.com/docs/flutter/setup?hl=en&platform=web

不在 firebase的 console 新建,而是用 command line 新建

先執行

firebase login

安裝 flutter_fire 的 cli

dart pub global activate flutterfire_cli

把app 跟 firebase 連在一起

flutterfire configure

按上下可以做選擇,選到 create a new project

  • 輸入 project name
  • 選擇平臺的地方,選擇 web android ios
  • 這個步驟會 create firebase_options.dartlib 的目錄下

遇到

  • The files android/build.gradle & android/app/build.gradle will be updated to apply Firebase configuration and gradle build plugins. Do you want to continue? (y/n):輸入 yes
  • Generated FirebaseOptions file lib/firebase_options.dart already exists, do you want to override it? (y/n) :輸入 yes

Initialize Firebase in your app

在 project 的根目錄下執行

flutter pub add firebase_core

lib/main.dart 裡面加入以下

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

lib/main.dart 裡面,先 initialize firebase

await Firebase.initializeApp(   options: DefaultFirebaseOptions.currentPlatform, );

執行看看是否正確。

在 Firebase project 裡建立 Firestore database

因為 firebase init 的時候會檢查有沒有 Firestore,所以先要在後臺把它 enable起來

在後臺建立一個 Firestore 的database

Initialize a Firebase project

要再用更多的 Firebase 功能,如 firestore 等,執行以下命令

firebase init

這裡比較常用的是以下兩個,把它們選起來繼續

  • Firestore: Configure security rules and indexes files for Firestore
  • Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys

如果一直遇到 It looks like you haven't used Cloud Firestore in this project before 的訊息,可以參考這一篇:https://stackoverflow.com/a/74532000,設定 Default GCP resource location

  • 設定的時候,有一些選項參考如下:
? What do you want to use as your public directory? public 
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? Set up automatic builds and deploys with GitHub? No

幫project建立一個alias

要佈署的時候,習慣使用簡化的 dev prod 等 stage名稱,可是專案多的時候,加入專案名字會太長,所以可以在firebase專案裡面建立 alias,讓以後佈署更方便,執行以下命令

firebase use --add

建立不同 stage 的 專案

執行以下命令來建立其它 stage 的專案

flutterfire configure
  • 把不同 stage 的 firebase_options.dar 獨立出來,e.g. 如果有用 devprod 不同 stage的話,我也會新建為 firebase_options_dev.dart還有 firebase_options_prod.dart 的不同檔案,待會兒再寫 script 來做 自動化佈署
  • 因為已經 flutter init 過了,所以直接在其它的專案裡面新建 Firestore database
  • 不同專案也建立不同的 alias 名稱
  • 建立完 alias之後,可以使用以下命令來切換對應到的Firebase 專案
firebase use dev 
firebase use prod

Deploy 到Firebase

使用以下腳本做自動化佈署,以下以 dev 為例

firebase use dev
cp firebase_options_dev.dart lib/firebase_options.dart
flutter build web
firebase deploy

測試看看 deploy 後的 url 是否有顯示成功。

--

--