今天,有个童鞋在我的博客 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
异常,是因为获取的PlatformViewFactory
为null
。
registry
是PlatformViewRegistryImpl.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