LoginSignup
4
0

More than 1 year has passed since last update.

[Flutter Web] onCallでCloud Functionsの関数を呼び出す

Posted at

この記事は、【 可茂IT塾 Advent Calendar 2021 】の10日目の記事です。

FlutterWebのアプリ作成で実装したことを記事にしました。
誰かのお役に立てれば、幸いです。

準備

Firebaseの初期設定は、

を参考にしてください。

CloudFunctionsの初期設定

pubspec.yamlに

dependencies:
  flutter:
    sdk: flutter
  firebase_core: "^0.7.0"
  cloud_functions: "^0.9.0" //追加

を追加して、$ flutter pub get

index.htmlにSDKを追加します。

<html>
  ...
  <body>
    <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-functions.js"></script> // 追加
  </body>
</html>

実装

ElevatedButtonを押すと、関数が呼び出されるようになっています。

import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('テスト'),
      ),
      body: Column(
        children: [
          const Text('テスト'),
          ElevatedButton(
            onPressed: () async {
              final functions = FirebaseFunctions.instanceFor(
                  app: Firebase.app(), region: 'asia-northeast1');
              final callable = functions.httpsCallable('FUNCTION NAME',
                  options: HttpsCallableOptions(
                      timeout: const Duration(seconds: 300)));
              await callable();
            },
            child: const Text('テスト'),
          ),
        ],
      ),
    );
  }
}

上のコード例では、リージョンや、タイムアウトなども設定して関数を呼び出すようにしています。

デプロイの際にリージョンを指定していなければ、下の形でも動きます。

ElevatedButton(
       onPressed: () async {
       final functions = FirebaseFunctions.instance;
       final callable = functions.httpsCallable('FUNCTION NAME');
       await callable();
     },

参考

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0