Flutter-通過channel傳遞大數(shù)據(jù)塊

Flutter側(cè)

  • 創(chuàng)建MethodChannel
  static const MethodChannel methodChannel =
      MethodChannel('OOAssetsMethodChannelName');
  • 管理channel的異步方法
  Future<void> _foo() async {
    Uint8List imageData;
    try {
      final result = await methodChannel.invokeMethod('foo');
      imageData = result;
    } on PlatformException {
      imageData = null;
    }
    setState(() {
      _imageData = imageData; //觸發(fā)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側(cè)

  • 注冊通道,并設(shè)置handle
    FlutterMethodChannel* methodChannel = [FlutterMethodChannel
                                            methodChannelWithName:@"OOAssetsMethodChannelName"
                                            binaryMessenger:BinaryMessenger;
    [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        if ([@"foo" isEqualToString:call.method]) {
            _result = result; //在每一個調(diào)用周期內(nèi),result是一次性的。
            [weakSelf getData];
        } else {
            result(FlutterMethodNotImplemented);
        }
    }];
  • encode data并將數(shù)據(jù)回傳給Flutter側(cè)
NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
_result ? _result(imageData) : nill;

Android側(cè)

  • 注冊通道,并設(shè)置handle
new MethodChannel(BinaryMessenger, OOAssetsMethodChannelName).setMethodCallHandler(
                (call, result) -> {
                    if (call.method.equals("foo")) {
                        this.result = result; //在每一個調(diào)用周期內(nèi),result是一次性的。
                        getData();
                    } else {
                        result.notImplemented();
                    }
                });
  • encode data并將數(shù)據(jù)回傳給Flutter側(cè)
  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();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容