転職したらスマレジだった件

スマレジのエンジニアやまてのテックブログです。マジレス大歓迎です。

Flutter アプリに Firebase を導入する手順

スマレジの テックファーム(SES 部門) でWebエンジニアとして働いている やまて(@r_yamate) と申します。

実務では 2023 年 3 月末まで、 SES の派遣先のテーブルオーダーシステムの機能改修の設計などを担当しました。

2023 年 4 月からは、スマレジの関連アプリの開発業務を担当しています。触ったことのなかった Flutter での開発で、日々奮闘中です。

はじめに

今回は、 Flutter アプリに Firebase を導入する手順についてまとめます。

具体的には、以下の Firebase の公式ドキュメントの「Flutter アプリに Firebase を追加する」を実際にやってみたハンズオンの記録に加えて、不明な点を調べてまとめたものです。

目次

環境

準備. ダッシュボードの確認と「アプリを追加」クリック

Firebase プロジェクトのダッシュボードの確認

Firebase コンソール で、作成したプロジェクトのダッシュボードが表示されるようになっています。

Firebase プロジェクトの作成をしていない場合は、作成が必要です。

ryamate.hatenablog.com

「アプリを追加」クリック

「アプリを追加」をクリックします。

プラットフォームの選択について、今回は Flutter を選択します。なお、現在(2023/08/15時点)は、AppleAndroid、ウェブ、Unity、Flutter を選択できます。

この「Flutter アプリに Firebase を追加する」という画面で以下のステップが表示されます。

この手順通りに進めます。

1. ワークスペースの準備

以下の「① ワークスペースの準備」のステップのとおり進めます。

1-1. Firebase CLI のインストール

ローカルPCでターミナルを開き、 Firebase CLI をインストールします。

firebase.google.com

以下の cURL コマンドを実行して、自動インストール スクリプトで Firebase CLI をインストールします。

curl -sL https://firebase.tools | bash

このスクリプトは、ご使用のオペレーティング システムを自動的に検出し、最新の Firebase CLI リリースをダウンロードしてから、グローバルに使用可能な firebase コマンドを有効にします。

実行時ログ

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [11:22:33]
$ curl -sL https://firebase.tools | bash
Password:
-- Checking for existing firebase-tools on PATH...
-- Checking your machine type...
-- Downloading binary from https://firebase.tools/bin/macos/latest
######################################################################## 100.0%#=#=#                                   ######################################################################## 100.0%%%%%%2%5.2%7%%%0%2.4%.9%
-- Setting permissions on binary...
-- Checking your PATH variable...
-- firebase-tools@11.25.2 is now installed
-- All Done!

1-2. firebase login でログイン

以下のコマンドを実行して、Google アカウントで Firebase にログインします。

firebase login

実行時ログ

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [11:23:22]
$ firebase login
i  Firebase optionally collects CLI and Emulator Suite usage and error reporting information to help improve our products. Data is collected in accordance with Google's privacy policy (https://policies.google.com/privacy) and is not used to identify you.

? Allow Firebase to collect CLI and Emulator Suite usage and error reporting information? (Y/n)

? Allow Firebase to collect CLI and Emulator Suite usage and error reporting information? Yes
i  To change your data collection preference at any time, run `firebase logout` and log in again.

Visit this URL on this device to log in:
https://accounts.google.com/o/oauth2/auth?client_id=~~(省略)~~

Waiting for authentication...

✔  Success! Logged in as ~~~@gmail.com

1-3. アカウントにアクセスしていることのテスト

以下のコマンドを実行して、Firebase プロジェクトを一覧表示し、CLI が正しくインストールされていて、アカウントにアクセスしていることをテストします。

firebase projects:list

アクセスできていれば、 Firebase コンソールと同じ Firebase プロジェクトが表示されます。

実行時ログ

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [11:28:12]
$ firebase projects:list
✔ Preparing the list of your Firebase projects
┌──────────────────────┬────────────────┬────────────────┬──────────────────────┐
│ Project Display Name │ Project ID     │ Project Number │ Resource Location ID │
├──────────────────────┼────────────────┼────────────────┼──────────────────────┤
│ Sample Project       │ sample-project │ 1234567890123  │ [Not specified]      │
└──────────────────────┴────────────────┴────────────────┴──────────────────────┘

1 project(s) total.

補足. 異なるアカウントでログインする場合

以下のコマンドを実行して、現在のログインをログアウトしてから新しいアカウントで再度ログインすれば、 Firebase CLI を使用して異なるアカウントでログインできます。

firebase logout

1-4. Flutter SDK のインストール

Flutter SDK をインストールします。(完了しているため、スキップします)

ryamate.hatenablog.com

1-5. Flutter プロジェクトの作成

Flutter プロジェクトを作成します。(完了しているため、スキップします)

ryamate.hatenablog.com

2. FlutterFire CLI のインストールと実行

「② FlutterFire CLI のインストールと実行」のステップについても、提示のとおり進めます。

2-1. FlutterFire CLI のインストール

任意のディレクトリから、以下のコマンドを実行して、 flutterfire_cli というコマンドラインツールをグローバルに有効にする操作を行います。

dart pub global activate flutterfire_cli

実行時ログ

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [11:30:58]
$ dart pub global activate flutterfire_cli
  ╔════════════════════════════════════════════════════════════════════════════╗
  ║ The Dart tool uses Google Analytics to report feature usage statistics     ║
  ║ and to send basic crash reports. This data is used to help improve the     ║
  ║ Dart platform and tools over time.                                         ║
  ║                                                                            ║
  ║ To disable reporting of analytics, run:                                    ║
  ║                                                                            ║
  ║   dart --disable-analytics                                                 ║
  ║                                                                            ║
  ╚════════════════════════════════════════════════════════════════════════════╝

+ ansi_styles 0.3.2+1s... (2.1s)
+ args 2.4.0
+ async 2.11.0
+ boolean_selector 2.1.1
+ characters 1.3.0
+ ci 0.1.0
+ cli_util 0.3.5 (0.4.0 available)
+ clock 1.1.1
+ collection 1.17.1
+ dart_console 1.1.2
+ deep_pick 0.10.0 (1.0.0 available)
+ ffi 2.0.1
+ file 6.1.4
+ flutterfire_cli 0.2.7
+ http 0.13.5
+ http_parser 4.0.2
+ interact 2.2.0
+ intl 0.17.0 (0.18.0 available)
+ json_annotation 4.8.0
+ matcher 0.12.15
+ meta 1.9.1
+ path 1.8.3
+ petitparser 5.1.0 (5.3.0 available)
+ platform 3.1.0
+ process 4.2.4
+ pub_semver 2.1.3
+ pub_updater 0.2.4
+ pubspec 2.3.0
+ quiver 3.2.1
+ source_span 1.9.1
+ stack_trace 1.11.0
+ stream_channel 2.1.1
+ string_scanner 1.2.0
+ term_glyph 1.2.1
+ test_api 0.5.1
+ tint 2.0.1
+ typed_data 1.3.1
+ uri 1.0.0
+ win32 2.7.0 (4.1.1 available)
+ xml 6.2.2
+ yaml 3.1.1
Downloading flutterfire_cli 0.2.7...
Downloading deep_pick 0.10.0...
Downloading cli_util 0.3.5...
Downloading ci 0.1.0...
Downloading ansi_styles 0.3.2+1...
Downloading platform 3.1.0...
Downloading interact 2.2.0...
Downloading dart_console 1.1.2...
Downloading intl 0.17.0...
Downloading tint 2.0.1...
Downloading win32 2.7.0...
Downloading ffi 2.0.1...
Downloading characters 1.3.0...
Downloading clock 1.1.1...
Downloading pubspec 2.3.0...
Downloading uri 1.0.0...
Downloading yaml 3.1.1...
Downloading pub_updater 0.2.4...
Downloading process 4.2.4...
Downloading meta 1.9.1...
Downloading file 6.1.4...
Downloading string_scanner 1.2.0...
Downloading http 0.13.5...
Downloading http_parser 4.0.2...
Downloading typed_data 1.3.1...
Downloading xml 6.2.2...
Downloading collection 1.17.1...
Downloading petitparser 5.1.0...
Downloading path 1.8.3...
Downloading args 2.4.0...
Downloading pub_semver 2.1.3...
Downloading quiver 3.2.1...
Downloading source_span 1.9.1...
Downloading term_glyph 1.2.1...
Downloading matcher 0.12.15...
Downloading async 2.11.0...
Downloading test_api 0.5.1...
Downloading stack_trace 1.11.0...
Downloading stream_channel 2.1.1...
Downloading boolean_selector 2.1.1...
Downloading json_annotation 4.8.0...
Building package executables... (6.0s)
Built flutterfire_cli:flutterfire.
Installed executable flutterfire.
Warning: Pub installs executables into $HOME/.pub-cache/bin, which is not on your path.
You can fix that by adding this to your shell's config file (.bashrc, .bash_profile, etc.):

  export PATH="$PATH":"$HOME/.pub-cache/bin"

Activated flutterfire_cli 0.2.7.

2-2. FlutterFire CLI の実行

続いて、Flutter プロジェクトのルートディレクトリで、以下のコマンドを実行します。

flutterfire configure --project=sample-project

実行すると、プラットフォームごとのアプリが Firebase に自動的に登録され、 lib/firebase_options.dart ファイルが Flutter プロジェクトに追加されます。

実行時ログ

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [12:31:21]
$ flutterfire configure --project=sample-project
i Found 1 Firebase projects. Selecting project sample-project.
? Which platforms should your configuration support (use arrow keys & space to select)? ›
✔ android
✔ ios
✔ macos
✔ web

複数のプラットフォームのうち、 ✔ を入れているプラットフォームについて、 Firebase プロジェクトに、新しいアプリが登録されます。

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [12:31:21]
$ flutterfire configure --project=sample-project
i Found 1 Firebase projects. Selecting project sample-project.
✔ Which platforms should your configuration support (use arrow keys & space to select)? · android, ios, macos, web
i Firebase android app com.example.sample-project is not registered on Firebase project sample-project.
i Registered a new Firebase android app on Firebase project sample-project.
i Firebase ios app com.example.sample-project is not registered on Firebase project sample-project.
i Registered a new Firebase ios app on Firebase project sample-project.
i Firebase macos app com.example.sample-project registered.
i Firebase web app sample-project (web) is not registered on Firebase project sample-project.
i Registered a new Firebase web app on Firebase project sample-project.
? The files android/build.gradle & android/app/build.gradle will be updated to apply Firebase config
✔ 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? · yes

Firebase configuration file lib/firebase_options.dart generated successfully with the following Firebase apps:

Platform  Firebase App Id
web       1:1023456789012:web:1c2e3cc4567a8901c2b34c
android   1:1023456789012:android:1c2e3cc4567a8901c2b34c
ios       1:1023456789012:ios:bb1234f5df6a7d8fc9b01c
macos     1:1023456789012:ios:bb1234f5df6a7d8fc9b01c

Learn more about using this file and next steps from the documentation:
 > https://firebase.google.com/docs/flutter/setup

補足. flutterfire コマンドが見つからないエラーの場合

なお、以下のエラーになった場合は、システムの PATH 内に flutterfire コマンドを追加します。

実行時ログ(エラー)

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [12:26:39]
$ flutterfire configure --project=sample-project
zsh: command not found: flutterfire

以下、編集の例です。

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [11:30:24] C:1
$ vim ~/.zshrc
# 以下を .zshrc に追記
export PATH="$PATH":"$HOME/.pub-cache/bin"

編集したら設定を反映します。

# r_yamate @ mbp in ~/StudioProjects/sample-project on git:main o [11:41:52]
$ source ~/.zshrc

3. Firebase の初期化とプラグインの追加

最後に「③ Firebase の初期化とプラグインの追加」のステップについてです。

以下の「ステップ 3: アプリで Firebase を初期化する」以降も詳細なドキュメントでしたので、こちらを主に参考にしながら進めました。

firebase.google.com

なお、Flutter プロジェクトに例えば Firebase Crashlytics を追加する場合は、以下の手順を加えて実行する必要があります。

firebase.google.com

3-1. コアプラグイン firebase_core の追加

Flutter のコアプラグイン firebase_core をインストールします。

プラグイン firebase_crashlytics の追加もまとめて実施することもできますが、ステップをわかりやすくするためを分けて実施します。)

pub.dev

firebase_core は、 Flutter で Firebase の各機能を利用するためのコアとなるパッケージです。具体的には、 Firebase の各プロダクトを Flutter アプリに統合するために、 Firebase SDK の初期化や設定を行うための基本的な関数やクラスが提供されています。

編集:pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
+  firebase_core: ^2.15.1

pub get を実行します。

flutter pub get

3-2. Firebase の初期化

lib/main.dart で、Firebase Core プラグインと、以前に生成した構成ファイル firebase_options.dart をインポートし、

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

以下のコードで Firebase を初期化します。

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

Firebase を初期化するには、新しい firebase_options.dart ファイルを使用して、firebase_core パッケージから Firebase.InitializeApp を呼び出します。

私の Flutter アプリの lib/main.dart では以下のように編集しました。

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'routers/router.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: goRouter,
    );
  }
}

3-3. flutterfire configure の再実行

flutterfire configure を再実行します。

flutterfire configure

これで Firebase の導入完了です。

おわりに

今回は Flutter アプリに Firebase を導入する方法についてまとめました。

これで、Firebase の各種プロダクトをアプリに導入する準備が整っています。 Firebase プロダクトの一つ Crashlytics の導入については以下の記事でまとめましたので、併せてご覧ください。

ryamate.hatenablog.com

ありがとうございました。



スマレジは 8/14〜16 がお盆休み。リゾート気分で過ごせました。in 淡路島。