Flutter--调用原生功能

Flutter工程调用原生功能--相册相机 demo

1 使用methodChannel

Flutter工程中创建MethodChannel

MethodChannel _methodChannel = MethodChannel('MethodChannelDemo'); //创建methodChannel需传入标识,一般可以使用类名来做标识

methodChannel调用方法

_methodChannel.invokeMapMethod('chooseImage', 'photo');    //传入方法名, 参数

原生工程中,监听FlutterMethodChannel

    FlutterViewController *flutterVC = (FlutterViewController *)self.window.rootViewController;

    self.methodChannel = [FlutterMethodChannel methodChannelWithName:@"MethodChannelDemo" binaryMessenger:flutterVC];

    UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];

    imageVC.delegate=self;

    //监听flutter消息

    [self.methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {

        if([call.methodisEqualToString:@"chooseImage"]) {

            if([call.argumentsisEqual:@"photo"]) {

                imageVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

            }

            if([call.argumentsisEqual:@"camera"]) {

                imageVC.sourceType = UIImagePickerControllerSourceTypeCamera;

            }

            [flutterVCpresentViewController:imageVC animated:YES completion:nil];

        }

    }];

原生工程,imagePickerDelegate回调,通过invokeMethod回调Flutter

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    [pickerdismissViewControllerAnimated:YES completion:^{

        NSString *imagePath = [NSString stringWithFormat:@"%@", info[@"UIImagePickerControllerImageURL"]];

        [self.methodChannel invokeMethod:@"imagePath" arguments:imagePath];

    }];

}

Flutter工程,接收回调,更换图片

File_imageFile;

@override

void initState() {

// TODO: implement initState

  super.initState();

  _methodChannel.setMethodCallHandler((handler) {

if (handler.method =='imagePath') {

String imagePath = handler.arguments.toString().substring(7);

      setState(() {

_imageFile =File(imagePath);

      });

    }

return null;

  });

}

Image(image: _imageFile ==null ? AssetImage('images/badge.png') : FileImage(_imageFile)),


2 使用image_picker

添加image_picker, Pug get,拉取包文件

Flutter--调用原生功能_第1张图片

void chooseImage()async {

PickedFile file = awaitImagePicker().getImage(source: ImageSource.gallery);

  setState(() {

_imageFile =File(file.path);

  });

}

你可能感兴趣的:(Flutter--调用原生功能)