🚀

Device Preview for Flutter、githubaction,firebasehostringを使って爆速レビューを目指す

2024/03/16に公開

目的

複数にflutterを開発する際に、自分のローカルにコードを入れて画面を確認するため、手間と時間がかかってしまっていた。そこでDevice Preview for Flutterを使い、web上に画面に出力を行うことでローカルでの確認を省くことにした。またgithubactionとfirebase hostringを使うことで自動化を行い、時間の削減を行なった。

実際のコード

https://github.com/nagisa599/flutter-firebasehostging-test

技術選定

今回は、vercelとfirebasehostringどちらを利用するか迷ったらが、 vercelの方は、previewとして作成したdeployを期間を決めて動かすことができる(基本10日)ため無駄なリソースを割かないで済むためfirebasehostringを利用した。

使用技術

  • cupertino_icons: ^1.0.6
  • device_preview: ^1.1.0

事前準備

flutterの構築

パッケージのインストール

https://pub.dev/packages/device_preview

flutter pub add device_preview

main.dartの変更

変更箇所

  • runAppの中にdevicePreviewの設定を追加
  • wightの中にbuilderとlocaleを設定
import 'package:flutter/material.dart';
import 'package:device_preview/device_preview.dart';

void main() {
  runApp(
    DevicePreview(
      enabled: true,
      tools: const [
        ...DevicePreview.defaultTools,
      ],
      builder: (context) => const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo4',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      builder: DevicePreview.appBuilder,
      locale: DevicePreview.locale(context),
      home: const MyHomePage(title: 'Flutter Demo Home Page2'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

firebase hostingの設定

firebasehostringのプロジェクトの作成

プロジェクトの設定は、こちらを参考に行いました。
https://zenn.dev/snova301/books/6df29a230d681f/viewer/8d8b4a

githubactionsの設定

FIREBASE_TOKENの取得

firebase login:ci

githubの設定

1. settingを選択
2. Secrets and variablesの中のactionを選択
3. Repository secretsにNew repository sercretでFIREBASE_TOKENを作成

github権限の変更

  1. settringを選択
  2. Actionのgenerlを選択
  3. Workflow permissionsをRead and write permissionsにチェック

ymlファイルへの記述

  • developへのpull requestがされたタイミング
  • developへのmergeされたタイミング
    この2つで実装を行いたいと思います。

developへのpull requestがされたタイミングのymlファイル

  • トリガーを設定する(onの部分)。
  • jobの中の仮想マシンは、ubuntuuの最新を選択。
  • stepの順序としては、
    • checkout(リポジトリをコピー)
    • setup flutter (subosito/fultter-actionのパッケージを使って環境を構築)
    • build web (web版としてbuild)
    • Deploy to Firebase Hosting Preview Channel(firebaseにdeploy)
      • channelId liveの時は本番環境(今回は、developに設定)
      • channnelIdを設定しない場合は、開発環境(preview) (今回は,pullrequest)の時
name: Deploy to Firebase Hosting Preview Channel

on:
  pull_request:
    branches:
      - develop

jobs:
  build_and_deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@v2

      - name: Setup Flutter
        uses: subosito/flutter-action@v1
        with:
          flutter-version: "3.x"

      - name: Build Web
        run: flutter build web

      - name: Deploy to Firebase Hosting Preview Channel
        uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: "${{ secrets.GITHUB_TOKEN }}"
          firebaseServiceAccount: "${{ secrets.FIREBASE_TOKEN }}"
          # channelId: live
          projectId: fir-hosting-test-e202b
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}

name: Deploy to Firebase Hosting on Merge

on:
  push:
    branches:
      - develop

jobs:
  build_and_deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@v2

      - name: Setup Flutter
        uses: subosito/flutter-action@v1
        with:
          flutter-version: "3.x"

      - name: Build Web
        run: flutter build web

      - name: Deploy to Firebase Hosting
        uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: "${{ secrets.GITHUB_TOKEN }}"
          firebaseServiceAccount: "${{ secrets.FIREBASE_TOKEN }}"
          channelId: live
          projectId: fir-hosting-test-e202b # あなたのFirebaseプロジェクトIDに置き換えてください
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}

補足・参考

https://zenn.dev/flutteruniv_dev/articles/flutter_device_preview
https://github.com/nagisa599/flutter-firebasehostging-test

おわりに,これから

開発環境のCI/CDの構築は、完了したので次は、本番環境(ios,andoroid)へのCI/CDの部分を作成していきたい。

Discussion