2023-01-11

【Flutter】Katana Functions

Cloud Functions for Firebaseなどのサーバー連携を行うためのアダプタープラグイン。

クライアント側にAPIとのインターフェースを実装して利用するためサーバー側とのやりとりを安全に行うことが可能です。

インストール

下記のパッケージをインポートします。

flutter pub add katana_functions

Cloud Functions for Firebaseを利用する場合は下記のパッケージも合わせてインポートします。

flutter pub add katana_functions_firebase

実装

事前準備

必ずFunctionsAdapterScopeのWidgetをアプリのルート近くに配置します。

adapterのパラメーターにRuntimeFunctionsAdapterといったFunctionsAdapterを渡します。

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return FunctionsAdapterScope(
      adapter: const RuntimeFunctionsAdapter(),
      child: MaterialApp(
        home: const FunctionsPage(),
        title: "Flutter Demo",
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
      ),
    );
  }
}

Functionの作成

Functionを作成するための前提として下記が遵守されていることが必須となります。

  • 予めサーバー側は別で実装を行いデプロイが完了している
  • サーバー側との入出力はすべてJsonMap(Map<String, dynamic>)で行われている
    • 最終的にFunctionsAdapterにて調整できれば問題なし
  • 通信が成功しなかった場合はExceptionを返す

上記が守られているのであれば、CloudFunctionsやRestAPI、GraphQL、gRPCなどどの通信形式でも対応可能です。(FunctionsAdapterにて差分を吸収可能)

FunctionsAction<TResponse>FunctionsActionResponseの抽象クラスを継承することでFunctionを作成します。

FunctionsAction<TResponse>のactionにFunctionのアクション名を定義し、toMap()にサーバー側に渡すためのパラメーターを定義します。

toResponse(DynamicMap map)にサーバーから帰ってきた値を元にレスポンスを作成します。

class TestFunctionsAction extends FunctionsAction<TestFunctionsActionResponse> {
  const TestFunctionsAction({
    required this.responseMessage,
  });

  final String responseMessage;

  @override
  String get action => "test";

  @override
  DynamicMap? toMap() {
    return {
      "message": responseMessage,
    };
  }

  @override
  TestFunctionsActionResponse toResponse(DynamicMap map) {
    return TestFunctionsActionResponse(
      message: map["message"] as String,
    );
  }
}

class TestFunctionsActionResponse extends FunctionsActionResponse {
  const TestFunctionsActionResponse({required this.message});

  final String message;
}

Functionの利用

下記のようにFunctionsのオブジェクトを作成し、executeメソッドに実行したいFunctionActionを渡してください。

実行が成功した場合executeの戻り値に指定したレスポンスが返ってきます。

final functions = Functions();
final response = await functions.execute(
  TestFunctionsAction(responseMessage: "Response"),
);
print(response?.message); // "Response"

FunctionsAdapter

下記のFunctionsAdapterが利用可能です。

  • RuntimeFunctionsAdapter:サーバーの処理を行わずエラーを出さずに完了するFunctionsAdapter。スタブとして利用可能です。
  • FirebaseFunctionsAdapter:FirebaseFunctionsを利用するためのFunctionsAdapter。actionがそのままFunctionの名前になります。

また、FunctionsAdapterを継承して自身で用意したRestAPIやGraphQL、gRPCと連携することも可能です。

GitHub Sponsors

スポンサーを随時募集してます。ご支援お待ちしております!

Developed the katana/masamune framework, which has dramatically improved the overall efficiency of Flutter-based application development.
https://github.comhttps://github.com
title