Flutter-通过channel传递大数据块

Flutter侧

  • 创建MethodChannel
  static const MethodChannel methodChannel =
      MethodChannel('OOAssetsMethodChannelName');
  • 管理channel的异步方法
  Future _foo() async {
    Uint8List imageData;
    try {
      final result = await methodChannel.invokeMethod('foo');
      imageData = result;
    } on PlatformException {
      imageData = null;
    }
    setState(() {
      _imageData = imageData; //触发build方法
    });
  }
  • 更新UI
  Widget _imageWidget(){
    if (_imageData != null) {
      return Image.memory(_imageData,
                      width: 200,
                      height: 200,
                    );
    }else{
      return Center(
        child: Text('I am not image'),
      );
    }
  }

iOS侧

  • 注册通道,并设置handle
    FlutterMethodChannel* methodChannel = [FlutterMethodChannel
                                            methodChannelWithName:@"OOAssetsMethodChannelName"
                                            binaryMessenger:BinaryMessenger;
    [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        if ([@"foo" isEqualToString:call.method]) {
            _result = result; //在每一个调用周期内,result是一次性的。
            [weakSelf getData];
        } else {
            result(FlutterMethodNotImplemented);
        }
    }];
  • encode data并将数据回传给Flutter侧
NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
_result ? _result(imageData) : nill;

Android侧

  • 注册通道,并设置handle
new MethodChannel(BinaryMessenger, OOAssetsMethodChannelName).setMethodCallHandler(
                (call, result) -> {
                    if (call.method.equals("foo")) {
                        this.result = result; //在每一个调用周期内,result是一次性的。
                        getData();
                    } else {
                        result.notImplemented();
                    }
                });
  • encode data并将数据回传给Flutter侧
  new Thread(() -> {
      Bitmap bitmap = BitmapFactory.decodeFile(imgurl);
      ByteBuffer allocate = ByteBuffer.allocate(bitmap.getByteCount());
      bitmap.copyPixelsToBuffer(allocate);

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
      byte[] byteArray = stream.toByteArray();
      bitmap.recycle();

      this.result.success(byteArray);
  }).start();

你可能感兴趣的:(Flutter-通过channel传递大数据块)