7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Flutter] アプリからCloudFunctionsの関数に引数を渡す、返り値を受け取る

Posted at

Flutterのアプリ作成で実装したことです。

何回も使いそうなので忘れないように記事にしておこうと思いました。

onRequestonCall で引数の渡し方、返り値の受け取り方が少し違います。

一度まとめておくと、次から調べる時間が短縮できるので。

このやり方以外にもあると思いますが、少しでも誰かのお役に立てれば、幸いに思います。

onRequestの場合

CloudFunctionsの関数

import * as functions from "firebase-functions";

export const testFunction = functions
  .region("asia-northeast1")
  .https.onRequest(async (request, response) => {
    const testVar = request.body.data.testVar;  // requestに格納されている引数を受け取る

    ...省略

    response.status(200).send({
      data: { resultVar: resultVar }, // responseに格納して、アプリに返り値を返す
    });
});

アプリ側

import 'package:cloud_functions/cloud_functions.dart';

final callable = FirebaseFunctions.instanceFor(region: 'asia-northeast1')
        .httpsCallable('testFunction');

final response = await callable.call({ 'testVar': testVar });  // 変数を渡す

final resultVar = response.data['resultVar'];  // 返り値を取り出す

onCallの場合

CloudFunctionsの関数

import * as functions from "firebase-functions";

export const testFunction = functions
  .region("asia-northeast1")
  .https.onCall(async (data, context) => {
    const testVar = data.testVar;  // dataに格納されている引数を受け取る

    ...省略
  
    return { resultVar };  // アプリ側に返り値を返す
  });

アプリ側

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

final functions = FirebaseFunctions.instanceFor(
    app: Firebase.app(), region: 'asia-northeast1');

final callable = functions.httpsCallable('testFunction');
final result = await callable({'testVar': testVar});  // 変数を渡す

final resultVar = result.data['resultVar'];  // 返り値を取り出す

参考にしたサイト

7
1
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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?