Flutter PlatformView的使用

PlatformView

//flutter端的基本使用
GestureDetector(
          onVerticalDragStart: (_) {},
          child: Platform.isAndroid
              ? AndroidView(
                  viewType: "webview",//对应原生端唯一表示字符串
                  creationParams: <String,String>{
                    "url":"http://www.baidu.com"
                  },//向原生传递参数
                  creationParamsCodec: const StandardMessageCodec(),//参数的编码,如果有参数,这个必须要
                  gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
                    new Factory<OneSequenceGestureRecognizer>(
                      () => new EagerGestureRecognizer(),
                    ),
                  ].toSet(),//手势处理
                )
              : UiKitView(
                  viewType: "webview",
                  creationParams: <String,String>{
                    "url":"http://www.baidu.com"
                  },
                  creationParamsCodec: const StandardMessageCodec(),
                  gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
                    new Factory<OneSequenceGestureRecognizer>(
                      () => new EagerGestureRecognizer(),
                    ),
                    
                  ].toSet(),
                ),
        )
//IOS端对应的实现:(object-c)

1、创建PlatformView实现类 遵循FlutterPlatformView
//头文件 IOSPlatformView.h
@interface IOSPlatformView : NSObject<FlutterPlatformView>

@end
//实现类 IOSPlatformView.m
@interface IOSPlatformView ()

@property(nonatomic,strong) WKWebView * webView;

@end

@implementation IOSPlatformView


- (WKWebView *)webView{
    if(_webView == nil){
        WKWebViewConfiguration *webConfiguration = [WKWebViewConfiguration new];
        _webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:webConfiguration];
        NSString *urlStr = @"https://www.baidu.com";
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [_webView loadRequest:request];
    }

    return _webView;
}


- (UIView *)view{
    return [self webView];
}
@end

2、声明对应的视图工厂类,遵循FlutterPlatformViewFactory协议

@interface IOSFlutterPlatformViewFactory : NSObject <FlutterPlatformViewFactory>

@end


@implementation IOSFlutterPlatformViewFactory

/**
 * 返回platformview实现类
 *@param frame 视图的大小
 *@param viewId 视图的唯一表示id
 *@param args 从flutter  creationParams 传回的参数
 *
 */
- (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id)args{
    //这里可以解析args参数,根据参数进行响应的操作
    return [[IOSPlatformView alloc]init];
}

//如果需要使用args传参到ios,需要实现这个方法,返回协议。否则会失败。
- (NSObject<FlutterMessageCodec> *)createArgsCodec{
    return [FlutterStandardMessageCodec sharedInstance];
}
@end

3、将工厂注册到flutter engine

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar{
    
    [registrar registerViewFactory:[[IOSFlutterPlatformViewFactory alloc] init] withId:@"webview"];
}

4、在info.plist中加入下面的 (关键步骤)

<key>io.flutter.embedded_views_preview</key>
<true/>

//Android 端对应的实现;(java)

1、实现PlatformView接口,

/**
 * @author Lupy Create on 2020/4/10.
 * @description
 */
public class AndroidPlatformView implements PlatformView {

    private WebView webView;
    private Context context;

    AndroidPlatformView(Context context){
        this.context = context;
        
        webView = new WebView(context);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return true;
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        webView.loadUrl("url");
    }
    @Override
    public View getView() {
        //这个方法会被频繁的调用,所以不应该在这里面直接new 一个原生视图;会导致滑动事件出问题。
        return webView;
    }

    @Override
    public void dispose() {
        webView.dispose();
    }
}


2、实现工厂类

/**
 * @author Lupy Create on 2020/4/10.
 * @description
 */
public class AndroidPlatformViewFactory extends PlatformViewFactory {
    public AndroidPlatformViewFactory() {
        super(StandardMessageCodec.INSTANCE);
    }

    /**
     * 创建PlatformView 
     * @param context 上下文
     * @param viewId 视图的id
     * @param args flutter端传回的参数
     * @return 返回一个PlatformView的实现类
     */
    @Override
    public PlatformView create(Context context, int viewId, Object args) {
        return new AndroidPlatformView(context);
    }
}

3、注册到flutter engine

 PlatformViewRegistry platformViewRegistry = registrar.platformViewRegistry();
 platformViewRegistry.registerViewFactory("webview",new AndroidPlatformViewFactory());

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容