Flutter 嵌入原生View报错 : Trying to create a platform view of unregistered type

今天,有个童鞋在我的博客 Flutter嵌入原生View,使用原生的WebView 上留言,说遇到了Trying to create a platform view of unregistered type的报错,想问一下有没有遇到过,怎么解决的。在此记录一下,希望能帮到有需要的其他童鞋。

我看了一下,rying to create a platform view of unregistered type这个报错是在PlatformViewsChannel.create() -> PlatformViewsController.createForPlatformViewLayer()中抛出的。

PlatformViewsChannel.java

private void create(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
	//...省略...
    handler.createForPlatformViewLayer(request);
	//...省略...
}

handler是一个PlatformViewsHandler.java类,我们来看下它的createForPlatformViewLayer方法

public void createForPlatformViewLayer(@NonNull PlatformViewCreationRequest request) {
	//...省略...
	PlatformViewFactory factory = PlatformViewsController.this.registry.getFactory(request.viewType);
	if (factory == null) {
	    throw new IllegalStateException("Trying to create a platform view of unregistered type: " + request.viewType);
	}
	//...省略...
}

可知,抛出Trying to create a platform view of unregistered type异常,是因为获取的PlatformViewFactorynull
registryPlatformViewRegistryImpl.java类,我们来看一下

class PlatformViewRegistryImpl implements PlatformViewRegistry {

  PlatformViewRegistryImpl() {
    viewFactories = new HashMap<>();
  }

  // Maps a platform view type id to its factory.
  private final Map<String, PlatformViewFactory> viewFactories;

  @Override
  public boolean registerViewFactory(String viewTypeId, PlatformViewFactory factory) {
    if (viewFactories.containsKey(viewTypeId)) return false;
    viewFactories.put(viewTypeId, factory);
    return true;
  }

  PlatformViewFactory getFactory(String viewTypeId) {
    return viewFactories.get(viewTypeId);
  }
}

可知,viewFactories是一个Map,故是因为没有调用过registerViewFactory方法,导致抛出的这个异常。

所以需要再检查下代码,哪里漏写了。
具体怎么嵌入原生View,可以看我的博客 Flutter嵌入原生View,使用原生的WebView

参考
flutter androidView实现原理


版权声明:本文为EthanCo原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。