Flutter官方推荐插件开发辅助工具-Pigeon

工具插件:pigeon

推荐必看的官方例子:pigeon_plugin_example

其他pigeon写法的例子:
pigeon/example
pigeons

Pigeon is a code generator tool to make communication between Flutter and the host platform type-safe, easier and faster.
一个代码生成工具,让Flutter和宿主平台更安全、更简单、更快地通信。

通过Dart入口,生成两端通用的模板代码,原生则只需重写模板内的接口,无需管理Method Channel的实现。参数可以通过模板来同步生成。

目前的pigeon只支持生成OCJava代码。

1、命令创建Plugin

$ flutter create --template=plugin --platforms=android,ios -i swift -a kotlin flutter_pigeon_plugin

2、flutter项目中pubspec.yamldev_dependencies中,添加pigeon插件依赖

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

  pigeon: 

3、在Flutter项目的lib目录外创建一个pigeons文件夹,在pigeons文件夹中创建all_types_pigeon.dart

import 'package:pigeon/pigeon.dart';

class Everything {
  bool? aBool;
  int? anInt;
  double? aDouble;
  String? aString;
  Uint8List? aByteArray;
  Int32List? a4ByteArray;
  Int64List? a8ByteArray;
  Float64List? aFloatArray;
  // ignore: always_specify_types
  List? aList;
  // ignore: always_specify_types
  Map? aMap;
  List<List<bool?>?>? nestedList;
  Map<String?, String?>? mapWithAnnotations;
}

/// Flutter调用原生的方法
@HostApi()
abstract class HostEverything {
  Everything giveMeEverything();
  Everything echo(Everything everything);
}

/// 原生调用Flutter的方法
@FlutterApi()
abstract class FlutterEverything {
  Everything giveMeEverythingFlutter();
  Everything echoFlutter(Everything everything);
}

4、执行命令

首先创建存放生成文件的文件夹:
android/src/mian下创建java/com/example/flutter_pigeon_plugin/文件夹,存放生成的Java文件。

在项目目录~/flutter_pigeon_plugin下,执行以下命令:
$ flutter pub run pigeon --input pigeons/all_types_pigeon.dart --dart_out lib/all_types_pigeon.dart --objc_header_out ios/Classes/AllTypesPigeon.h --objc_source_out ios/Classes/AllTypesPigeon.m --java_out android/src/main/java/com/example/flutter_pigeon_plugin/AllTypesPigeon.java --java_package "com.example.flutter_pigeon_plugin"

命令拆解:
①` flutter pub run pigeon`  
生成代码的命令

②` --input pigeons/all_types_pigeon.dart `
指定生成代码的输入`dart`文件

③ `--dart_out lib/all_types_pigeon.dart `
指定输出生成`dart`文件的目录文件

④ `--objc_header_out ios/Classes/AllTypesPigeon.h  `
指定要生成的`iOS`的`.h`文件路径

⑤ `--objc_source_out ios/Classes/AllTypesPigeon.m  `
指定要生成的`iOS`的`.m`文件路径

⑥ `--java_out android/src/main/java/com/example/flutter_pigeon_plugin/AllTypesPigeon.java `
指定要生成的`Android`的`.java`文件路径

⑦  `--java_package "com.example.flutter_pigeon_plugin`
指定`Android`的包名,在`android/src/main/`下的`AndroidManifest.xml`里的`package`

⑧ `--objc_prefix FLT`(可?。┲付ㄉ蒓C文件的前缀为FLT,前缀自己定义为自己的。

可以参考官方的例子里的做法:
① 项目目录下创建一个run_pigeon.sh文件
② 每次有改动,执行命令:. ./run_pigeon.sh即可
run_pigeon.sh文件内容如下:

flutter pub run pigeon \
  --input pigeons/all_types_pigeon.dart \
  --dart_out lib/all_types_pigeon.dart \
  --objc_header_out ios/Classes/AllTypesPigeon.h \
  --objc_source_out ios/Classes/AllTypesPigeon.m \
  --objc_prefix FLT \
  --java_out android/src/main/java/com/example/flutter_pigeon_plugin/AllTypesPigeon.java \
  --java_package "com.example.flutter_pigeon_plugin"

命令执行完成,会自动在命令中指定的几个位置生成响应的文件。

5、iOS实现Flutter调用原生的方法

① 删掉项目中之前的获取版本的原生的和Flutter侧的相关channel代码
② 在AllTypesPigeon.m中自动生成了一个方法HostEverythingSetup

void HostEverythingSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<HostEverything> *api) {
  {
    FlutterBasicMessageChannel *channel =
      [FlutterBasicMessageChannel
        messageChannelWithName:@"dev.flutter.pigeon.HostEverything.giveMeEverything"
        binaryMessenger:binaryMessenger
        codec:HostEverythingGetCodec()];
    if (api) {
      NSCAssert([api respondsToSelector:@selector(giveMeEverythingWithError:)], @"HostEverything api doesn't respond to @selector(giveMeEverythingWithError:)");
      [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
        FlutterError *error;
        Everything *output = [api giveMeEverythingWithError:&error];
        callback(wrapResult(output, error));
      }];
    }
    else {
      [channel setMessageHandler:nil];
    }
  }
  {
    FlutterBasicMessageChannel *channel =
      [FlutterBasicMessageChannel
        messageChannelWithName:@"dev.flutter.pigeon.HostEverything.echo"
        binaryMessenger:binaryMessenger
        codec:HostEverythingGetCodec()];
    if (api) {
      NSCAssert([api respondsToSelector:@selector(echoEverything:error:)], @"HostEverything api doesn't respond to @selector(echoEverything:error:)");
      [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
        NSArray *args = message;
        Everything *arg_everything = args[0];
        FlutterError *error;
        Everything *output = [api echoEverything:arg_everything error:&error];
        callback(wrapResult(output, error));
      }];
    }
    else {
      [channel setMessageHandler:nil];
    }
  }
}

③ 在SwiftFlutterPigeonPlugin.swift的注册方法里,调用这个setup方法进行初始化和设置

    public static func register(with registrar: FlutterPluginRegistrar) {
        let messenger: FlutterBinaryMessenger = registrar.messenger()
        let api: HostEverything & NSObjectProtocol = SwiftFlutterPigeonPlugin.init()
        HostEverythingSetup(messenger, api)
    }

SwiftFlutterPigeonPlugin遵循HostEverything协议,实现Flutter调原生的方法

import Flutter
import UIKit

/// 遵循HostEverything协议,实现Flutter调原生的方法
public class SwiftFlutterPigeonPlugin: NSObject, FlutterPlugin, HostEverything {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let messenger: FlutterBinaryMessenger = registrar.messenger()
        let api: HostEverything & NSObjectProtocol = SwiftFlutterPigeonPlugin.init()
        HostEverythingSetup(messenger, api)
    }

    // MARK: HostEverything

    public func giveMeEverythingWithError(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> Everything? {
        let everyThing = Everything()
        everyThing.aString = "原生返给Flutter的字符串"
        everyThing.aBool = false
        everyThing.anInt = 11
        return everyThing
    }

    /// 遵循HostEverything协议,实现Flutter调原生的方法
    public func echo(_ everything: Everything, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> Everything? {
        everything.aString = "原生交换的给Flutter的字符串"
        everything.aBool = false
        everything.anInt = 12
        return everything
    }
}

iOS/Classes目录下,创建flutter_pigeon_plugin.h文件,导入头文件,此文件在iOS自动生成的<flutter_pigeon_plugin/flutter_pigeon_plugin-Swift.h>文件中会自动引用。

//
//  flutter_pigeon_plugin.h
//  Pods
//
//  Created by yuanzhiying on 2021/9/13.
//

#ifndef flutter_pigeon_plugin_h
#define flutter_pigeon_plugin_h

#import "AllTypesPigeon.h"

#endif /* flutter_pigeon_plugin_h */

6、 flutter_pigeon_plugin.dart中实现插件调原生方法

import 'dart:async';

import 'package:flutter_pigeon_plugin/all_types_pigeon.dart';

class FlutterPigeonPlugin {
  static final HostEverything _hostEverything = HostEverything();

  /// Flutter 调用原生方法
  static Future<Everything> getEverything() async {
    return await _hostEverything.giveMeEverything();
  }

  /// Flutter 调用原生方法
  static Future<Everything> echoEveryThing(Everything everything) async {
    return await _hostEverything.echo(everything);
  }
}

7、使用插件的方法

  Future<void> getHostData() async {
    /// 通过插件调用原生方法
    Everything everything = await FlutterPigeonPlugin.getEverything();
    debugPrint('everything.aString: ${everything.aString}');
    debugPrint('everything.aBool: ${everything.aBool}');
    debugPrint('everything.anInt:${everything.anInt}');
  }

  void echoHostData() async {
    Everything echoEveryThing = Everything();
    echoEveryThing.aString = '我要跟原生交换的字符串';
    echoEveryThing.aBool = true;
    echoEveryThing.anInt = 10;

    /// 通过插件调用原生方法
    Everything everything = await FlutterPigeonPlugin.echoEveryThing(echoEveryThing);
    debugPrint('everything.aString: ${everything.aString}');
    debugPrint('everything.aBool: ${everything.aBool}');
    debugPrint('everything.anInt:${everything.anInt}');
  }

至此,flutter调用原生iOS方法完成。

8、flutter调用安卓原生的实现

① 删除原有的获取版本号的channel的代码
FlutterPigeonPlugin.kt中继承AllTypesPigeon.HostEverything,并实现对应的方法

  override fun giveMeEverything(): AllTypesPigeon.Everything {
    var everything: AllTypesPigeon.Everything = AllTypesPigeon.Everything()
    everything.aString = "原生返给Flutter的字符串"
    everything.aBool = false
    everything.anInt = 11
    return everything
  }

  override fun echo(everything: AllTypesPigeon.Everything?): AllTypesPigeon.Everything? {
    everything?.aString = "原生交换的给Flutter的字符串"
    everything?.aBool = false
    everything?.anInt = 12
    return everything
  }

③ 通过自动生成的setup方法,进行初始化和设置

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    AllTypesPigeon.HostEverything.setup(flutterPluginBinding.binaryMessenger, this)
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    AllTypesPigeon.HostEverything.setup(binding.binaryMessenger, null)
  }

最终如下:

package com.example.flutter_pigeon_plugin

import androidx.annotation.NonNull

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** FlutterPigeonPlugin */
class FlutterPigeonPlugin: FlutterPlugin, MethodCallHandler, AllTypesPigeon.HostEverything {

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    AllTypesPigeon.HostEverything.setup(flutterPluginBinding.binaryMessenger, this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    result.notImplemented()
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    AllTypesPigeon.HostEverything.setup(binding.binaryMessenger, null)
  }

  override fun giveMeEverything(): AllTypesPigeon.Everything {
    var everything: AllTypesPigeon.Everything = AllTypesPigeon.Everything()
    everything.aString = "原生返给Flutter的字符串"
    everything.aBool = false
    everything.anInt = 11
    return everything
  }

  override fun echo(everything: AllTypesPigeon.Everything?): AllTypesPigeon.Everything? {
    everything?.aString = "原生交换的给Flutter的字符串"
    everything?.aBool = false
    everything?.anInt = 12
    return everything
  }
}

项目代码见:flutter_pigeon_plugin

最后编辑于
?著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,029评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,238评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,576评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,214评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,324评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,392评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,416评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,196评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,631评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,919评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,090评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,767评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,410评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,090评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,328评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,952评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,979评论 2 351

推荐阅读更多精彩内容