Flutter调用原生代码

参考项目

dart中代码

  1. 注册MethodChannel
1
2
3
4
class DartMethodChannel {
    static const MethodChannel _channel =
        MethodChannel('flutter.method.channel/test'); //名字可以随便取
}
  1. 通过MethodChannel调用原生代码中的方法
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class DartMethodChannel {
  ...
  static Future<Object> toNativeFunction(
    int mode, Uint8List? imageByte,) async {
    var args = <String, dynamic>{
      "arg1": imageByte,
      "arg2": mode,
    };
    var result = await _channel.invokeMethod('nativeFunction', args);
    return result;
  }
}

其中'nativeFunction'是原生代码中需要调用的方法名,args为传参
result是原生代码给的结果

原生代码中的处理

  1. Android
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 创建监听类
public class AndroidMethodCallHandler implements FlutterPlugin, MethodCallHandler {

    private MethodChannel channel;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        // 名字需要与在flutter中定义的MethodChannel相同
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter.method.channel/test");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        // call就是flutter调用的具体参数
        // call.method就是调用了哪个方法
        // call.arguments就是调用方法传递的参数
        switch (call.method) {
            case "nativeFunction":
                // 获取参数1的数据
                byte[] data = ((Map<String, byte[]>) call.arguments).get("arg1");
                // 获取参数2的数据
                int mode = ((Map<String, Integer>) call.arguments).get("arg2");
                String receiptInfo = androidFunction(data, mode);
                // 将处理结果返回给flutter
                result.success(receiptInfo);
                break;
            default:
                result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    public String androidFunction(byte[] data, int mod){
        // 此处可以处理从flutter接收到的参数并返回结果
        ...
        ...
        ...
        return result;
    }
}
  1. ios
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 创建监听类
public class IOSMethodCallHandler: NSObject, FlutterPlugin {

    public static func register(with registrar: FlutterPluginRegistrar) {
        // 名字需要与在flutter中定义的MethodChannel相同
        let channel = FlutterMethodChannel(name: "flutter.method.channel/test", binaryMessenger: registrar.messenger())
        let instance = SwiftCasioOcrLibPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

    // 处理flutter发起的调用
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        // call就是flutter调用的具体参数
        // call.method就是调用了哪个方法
        // call.arguments就是调用方法传递的参数
        let method = call.method
        if method == "nativeFunction" {
            // 获取参数
            if let arguments = call.arguments as? [String: AnyObject] {
                // 将参数1取出来
                if let data: FlutterStandardTypedData = (arguments["arg1"] as? FlutterStandardTypedData) {
                    // 转化为image对象
                    if let uiImage = UIImage(data: data.data) {
                        let size = uiImage.size
                        // 取得参数2
                        if let mode = arguments["arg2"] as? Int32 {
                            // 调用原生代码进行处理
                            let result = iosFunction(uiImage, mode)
                            // 将结果返回给flutter
                            result(result)
                        }
                    } else {
                        result("error")
                    }
                } else {
                    result("error")
                }
            } else {
                result("error")
            }
        }
    }

    func iosFunction(_ images: [UIImage], _ mode: Int) -> String {
        // 对数据进行处理
        ...
        ...
        ...
        // 将结果返回给flutter
        return result
    }
}

dart中实际调用

1
2
// 直接调用即可
DartMethodChannel.toNativeFunction(mode, image)