Flutter & Firebase プロジェクト作成からエミュレータ環境構築まで(FlutterFireを用いた方法)

Flutter & Firebase プロジェクト作成からエミュレータ環境構築まで(FlutterFireを用いた方法)

March 12, 2022

前置き:前回投稿した同内容の記事について #

前回、本記事と同様の環境構築を目的とした記事を投稿しています。その手順は Firebase 公式の以下ページを参考に記載しました。

しかし、現在ではこれを FlutterFire CLI を用いてより簡単に行うことができることを知りました。本記事では FlutterFire CLI を用いたプロジェクト環境構築の手順を記載します。

前回の記事の手順に問題があるわけではありませんが、わざわざそうする必要がないため、今後は本記事の方法を採用するのが良いかと。FlutterFire のページでも FlutterFire CLI を使用しない構築方法(Manual Installation)は推奨されていません。

CAUTION

Manual installation is not the recommended installation flow. These guides are for existing applications using FlutterFire.

In previous versions of FlutterFire, in order to add Firebase to your projects manual platform specific steps were required, such as downloading a google-services.json file for Android, downloading a GoogleService-Info.plist file for iOS or editing your index.html file for web.

FlutterFire now supports initialization from Dart using the FlutterFire CLI.

参照 #

こちらの記事に従って作業していけば良い。

以降の作業は上記記事をもとに、順番を入れ替えて実施している。

0. Firebase CLI をインストール #

FlutterFire CLI は Firebase CLI に依存しているため Firebase CLI が必要。未インストールならば入れておくこと。

INFO

The FlutterFire CLI depends on the Firebase CLI.

1. FlutterFire CLI をインストール #

下記を実行するとグローバルにインストールされる。

dart pub global activate flutterfire_cli

その後確認のため以下を実行。

dart pub global list

flutterfire_cli の名称が出力されていればインストールできている。

インストールの最後に以下のメッセージが表示されていた。

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"

パスを通すかは好みだが、設定するならば .zshrc(私の場合)に export PATH="$PATH":"$HOME/.pub-cache/bin" を追加する。

2. Flutter プロジェクトの作成 #

flutter create -i swift -a kotlin my_flutter_app

その後、Android エミュレータと iOS シミュレータを立ち上げてカウンターアプリが表示されることを確認する。

flutter run

3. FlutterFire CLI でプロジェクト設定を作成 #

プロジェクトのディレクトリで以下を実行する。

flutterfire configure

# パスを通していない場合は以下で実行
# ~/.pub-cache/bin/flutterfire configure

先に Firebase プロジェクトを作成しており、それに紐づけるのであればそのプロジェクトを、新規でプロジェクトを作成するのであれば <create a new project> を選択する。

i Found 3 Firebase projects.
? Select a Firebase project to configure your Flutter application with ›
❯ my-first-sample-project (my-first-sample-project)
  my-second-sample-project (my-second-sample-project)
  my-third-sample-project (my-third-sample-project)
  <create a new project>

今回は <create a new project> を選択する。

ウィザードの質問に答えていく。以下は回答例。

i Found 3 Firebase projects.
✔ Select a Firebase project to configure your Flutter application with · <create a new project>

✔ Enter a project id for your new Firebase project (e.g. my-cool-project) · my-super-cool-flutter-project
i New Firebase project my-super-cool-flutter-project created succesfully.

? Which platforms should your configuration support (use arrow keys & space to select)? ›
✔ android
✔ ios
  macos
✔ web

✔ Which ios bundle id do you want to use for this configuration, e.g. 'com.example.app'? · com.example.app
i Registered a new Firebase ios app on Firebase project my-super-cool-flutter-project.
i Registered a new Firebase web app on Firebase project my-super-cool-flutter-project.

Firebase configuration file lib/firebase_options.dart generated successfully with the following Firebase apps:
Platform  Firebase App Id
web       1:************:web:0123456789abcdefghijkl
android   1:************:android:0123456789abcdefghijkl
ios       1:************:ios:0123456789abcdefghijkl

上記完了後、Firebase コンソールを開くと、指定した名称のプロジェクトが作成されており、その中に指定したアプリ(上記では android, ios, web)が設定されていることが確認できる。

ローカルでは firebase_options.dart が作成されており、内容は以下のようになっている。

// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
    show defaultTargetPlatform, kIsWeb, TargetPlatform;

/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
///   options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
  static FirebaseOptions get currentPlatform {
    if (kIsWeb) {
      return web;
    }
    // ignore: missing_enum_constant_in_switch
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
        return android;
      case TargetPlatform.iOS:
        return ios;
      case TargetPlatform.macOS:
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for macos - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
    }

    throw UnsupportedError(
      'DefaultFirebaseOptions are not supported for this platform.',
    );
  }

  static const FirebaseOptions web = FirebaseOptions(
    // ...
  );

  static const FirebaseOptions android = FirebaseOptions(
    // ...
  );

  static const FirebaseOptions ios = FirebaseOptions(
    // ...
  );
}

4. firebase_core プラグインをインストール #

プロジェクトのディレクトリで以下を実行する。(あるいは pubspec.yamlfirebase_core を記載してインストール。)

flutter pub add firebase_core
dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.0.0

5. コードを編集 #

lib/main.dart を以下の通り編集する。

// import を追加
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

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

ここまででセットアップは完了。

Android エミュレータと iOS シミュレータを立ち上げてカウンターアプリがこれまで通り表示されることを確認する。

以降は各自が使用する Firebase サービスのプラグインを追加してアプリを開発していく。

今回は Realtime Database のプラグインを追加して接続確認までを実施する。

6. Realtime Database と接続 #

参照元 #

6-1. Firebase コンソールから Realtime Database を有効化 #

(省略)

6-2. firebase_database プラグインをインストール #

flutter pub add firebase_database
dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.0.0
  firebase_database: ^9.0.0

6-3. シミュレータ・エミュレータ起動時のエラーを解消 #

firebase_database をインストールした後で起動確認、エラーが出るなら対応する。

6-3-1. iOS の要求バージョン指定をあげる #

iOS シミュレータを立ち上げると以下のエラーが出たので対応。

Launching lib/main.dart on iPhone 13 in debug mode...

(省略)

Specs satisfying the `firebase_database (from `.symlinks/plugins/firebase_database/ios`)` dependency were found, but they required a higher minimum deployment target.

(省略)

[!] Automatically assigning platform `iOS` with version `9.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile.

ios/Podfile を編集する。

# [更新前]
# platform :ios, '9.0'

# [更新後]
platform :ios, '10.0'

6-3-2. Android SDK の要求バージョン指定をあげる #

Android エミュレータを立ち上げると以下のエラーが出たので対応。

┌─ Flutter Fix ──────────────────────────────────────────────────────────────────────────────────────────────┐
│ The plugin firebase_database requires a higher Android SDK version.                                        │
│ Fix this issue by adding the following to the file android/app/build.gradle:                               │
│ android {│   defaultConfig {│     minSdkVersion 19}}│                                                                                                            │
│                                                                                                            │
│ Note that your app won't be available to users running Android SDKs below 19.                              │
│ Alternatively, try to find a version of this plugin that supports these lower versions of the Android SDK. │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

android/app/build.gradle を編集する。

// [更新前]
android {
    defaultConfig {
        minSdkVersion flutter.minSdkVersion
    }
}

// [更新前]
android {
    defaultConfig {
        minSdkVersion 21
    }
}

シミュレータ・エミュレータの起動が確認できたら次に進む。

6-4. コードを編集 #

lib/main.dart を以下の通り編集する。

// import を追加
import 'package:firebase_database/firebase_database.dart';

// _incrementCounter() を編集
void _incrementCounter() {
  FirebaseDatabase database = FirebaseDatabase.instance;
  DatabaseReference ref = database.ref().child('count');

  _counter++;

  ref.set(_counter);

  setState(() {
    _counter;
  });
}

iOS シミュレータと Android エミュレータ上でカウントボタンをタップする。(_incrementCounter() を実行する。)

画面上のカウンタが更新されること、Firebase Realtime Database にも同様のデータが保存されていることを確認する。


これで FlutterFire CLI を用いた Flutter プロジェクトの作成と Firebase との接続はすべて完了。


Firebase エミュレータ環境の作成は前回記事を参照 #

前回の記事では、ここからさらにローカルで開発するための Firebase エミュレータ環境の作成も行っているため、合わせてそちらも参照のこと。