1
0

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 3 years have passed since last update.

WindowsネイティブコードからDartの処理を呼ぶ

Posted at

Dart側の実装

StatefulWidgetを継承したクラスにて、MethodCannelを登録します。
戻り値でオブジェクトを返すことができます。

main.dart
  @override
  initState() {
    super.initState();
    const MethodChannel('domain/appname').setMethodCallHandler((call) {
      switch (call.method) {
        case 'testMethod':
          return Future.value("true");
        default:
          throw MissingPluginException();
      }
    });
  }

#Windowsネイティブ側の実装

flutter_window.cppのOnCreateメソッドの末尾に処理を追加します。

windows/runner/flutter_window.cpp
#include "flutter/generated_plugin_registrant.h"
#include "flutter/method_channel.h"
#include "flutter/standard_method_codec.h"
#include "flutter/method_result.h"
#include "flutter/method_result_functions.h"

bool FlutterWindow::OnCreate() {
  ...
  const std::string test_channel("domain/appname");
  const flutter::StandardMethodCodec& codec = flutter::StandardMethodCodec::GetInstance();

  flutter::MethodChannel method_channel_(flutter_controller_->engine()->messenger(), test_channel, &codec);

  auto result_handler = std::make_unique<flutter::MethodResultFunctions<>>(
    [](const flutter::EncodableValue* success_value) {
      std::cout << "on_success" << std::endl;
      std::cout << std::get<std::string>(*success_value) << std::endl;
    },
    [](std::string error_code, std::string error_message, const flutter::EncodableValue* error_details) {
      std::cout << "on_error" << std::endl;
    },
    []() {
      std::cout << "on_not_implemented" << std::endl;
    }
    );

  method_channel_.InvokeMethod("testMethod", nullptr, std::move(result_handler));
}

参考文献

MethodResultFunctionsの書き方が調べてもでなかったため、エンジンのテストコードを参考にしました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?