flutter开发实战-flutter web加载html及HtmlElementView的web控件
HtmlElementView 是 Flutter 中用于嵌入 HTML 内容的 widget。这个 widget 允许你将一个 HTML 元素嵌入到 Flutter 应用中。
一、HtmlElementView基本使用
在工程的pubspec.yaml中引入插件
HtmlElementView(
viewType: 'my-html-element-view-type',
)
其中viewType 是一个字符串,它告诉 Flutter 和宿主环境如何识别和嵌入的 HTML 元素。
要注意的是,HtmlElementView 目前只能在 Web 平台上工作,也就是说它只能在 Flutter 的 Web 应用中使用。在移动设备或桌面应用中是无法使用的。
二、ui.platformViewRegistry
使用HtmlElementView的同时,我们需要使用ui.platformViewRegistry来传入html的元素。HtmlElement()是基类,可以更加需要传入IFrameElement、HtmlHtmlElement、MediaElement、BodyElement等等元素。
需要注意的是HtmlElementView的viewType与registerViewFactory需要保持一致。
- 加载URL IFrameElement
ui.platformViewRegistry.registerViewFactory('html-viewType',
(int viewId) => IFrameElement()
..style.border = 'none'
..src = 'https://www.baidu.com');
加载URL需要http或者https这scheme,请写全。
- 加载Assets中HTML IFrameElement
ui.platformViewRegistry.registerViewFactory('html-viewType',
(int viewId) => IFrameElement()
..style.border = 'none'
..src = '/assets/test2.html');
- 加载Html字符串 HtmlHtmlElement
ui.platformViewRegistry.registerViewFactory('html-viewType',
(int viewId) => HtmlHtmlElement()
..style.border = 'none'
..setInnerHtml(html));
使用HtmlHtmlElement可以加载篇幅较短的html字符串。
- 加载图片 ImageElement
ui.platformViewRegistry.registerViewFactory('html-viewType',
(viewId) => ImageElement()
..src = 'https://example.com/image.png'
..style.width = '100px'
..style.height = '100px',);
使用ui.platformViewRegistry.registerViewFactory可能会报错。需要引入dart.html
三、使用flutter build web
使用命令进行打包
flutter build web --web-renderer html

四、小结
flutter开发实战-flutter web加载html及HtmlElementView的web控件
学习记录,每天不停进步。







![[图解]识别类和属性-投资少见效快产量高](https://i-blog.csdnimg.cn/direct/a1757c73b34e4a3da0af8cd4029ba1bb.png)









![[情商-13]:语言的艺术:何为真实和真相,所谓真相,就是别人想让你知道的真相!洞察谎言与真相!](https://i-blog.csdnimg.cn/direct/4e5ed3724fee417cadec420535421736.png)