Flutter侧
static const MethodChannel methodChannel =
MethodChannel('OOAssetsMethodChannelName');
Future<void> _foo() async {
Uint8List imageData;
try {
final result = await methodChannel.invokeMethod('foo');
imageData = result;
} on PlatformException {
imageData = null;
}
setState(() {
_imageData = imageData; //触发build方法
});
}
Widget _imageWidget(){
if (_imageData != null) {
return Image.memory(_imageData,
width: 200,
height: 200,
);
}else{
return Center(
child: Text('I am not image'),
);
}
}
iOS侧
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侧
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();