I'm sometimes receiving HTML as a response from network requests. I've encountered a scenario where I need to display HTML content within the InAppWebView. Is there any short way to do that.
I tried to find answer on the Internet, but couldn't.
Turns out we can do it through initialData parameter:
InAppWebView(
initialData: InAppWebViewInitialData(data: htmlExample),
)
const String htmlExample = '''
<!DOCTYPE html><html>
<head><title>HTML wxample</title></head>
<body>
<p>
HTML example
</p>
<ul>
<ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
<ul><a href="https://www.google.com/">https://www.google.com/</a></ul>
</ul>
</body>
</html>
''';
Also with InAppWebViewController:
webViewController.loadData(htmlExample);
To display HTML Content you can either use the Html Widget or the Core one with less dependencies. Html Widget Core.
Here an usage example from the pub.dev website:
HtmlWidget(
// the first parameter (`html`) is required
'''
<h3>Heading</h3>
<p>
A paragraph with <strong>strong</strong>, <em>emphasized</em>
and <span style="color: red">colored</span> text.
</p>
''',
// all other parameters are optional, a few notable params:
// specify custom styling for an element
// see supported inline styling below
customStylesBuilder: (element) {
if (element.classes.contains('foo')) {
return {'color': 'red'};
}
return null;
},
customWidgetBuilder: (element) {
if (element.attributes['foo'] == 'bar') {
// render a custom widget that takes the full width
return FooBarWidget();
}
if (element.attributes['fizz'] == 'buzz') {
// render a custom widget that inlines with surrounding text
return InlineCustomWidget(
child: FizzBuzzWidget(),
)
}
return null;
},
// this callback will be triggered when user taps a link
onTapUrl: (url) => print('tapped $url'),
// select the render mode for HTML body
// by default, a simple `Column` is rendered
// consider using `ListView` or `SliverList` for better performance
renderMode: RenderMode.column,
// set the default styling for text
textStyle: TextStyle(fontSize: 14),
),