Hello and welcome to FlutterCentral.com!
In this short and but very useful tutorial, we are going to learn how to add display HTML content inside a flutter app using **flutter_html package. **Sometimes you just want to display very less content in your app that is in HTML and webview isn't the most optimal way to go. In such a situation, this package will come to your rescue!
Before moving forward, let's see an illustration as to what we will be able to achieve at the end of this tutorial.
**STEPS TO REPRODUCE:**
**
**
**
**
- Adding package dependency in pubspec.yaml file
- Use the following code in your main.dart file
_MyHomePageState();
}
class _MyHomePageState extends State {
String htmlOpeningString = "";
String htmlContentString =
"An H1 HeadingThis is a paragraph. Cillum excepteur aliquip nisi ex enim ut occaecat.";
String htmlClosingString = "";
String normalText = "This is normal flutter text widget!";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Html(
data: htmlOpeningString +
htmlContentString +
htmlClosingString, //html string to be parsed
useRichText: true,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
defaultTextStyle: TextStyle(fontSize: 14),
imageProperties: ImageProperties(
//formatting images in html content
height: 150,
width: 150,
),
onImageTap: (src) {
setState(() {
normalText = 'You just clicked on the flutter logo!';
});
},
onLinkTap: (url) {
// open url in a webview
},
//(optional) used for override dom elements formatting
customTextStyle: (dom.Node node, TextStyle baseStyle) {
if (node is dom.Element) {
switch (node.localName) {
case 'h1':
return baseStyle.merge(TextStyle(fontSize: 20));
case 'p':
return baseStyle.merge(TextStyle(fontSize: 18));
}
}
},
),
SizedBox(
height: 30,
),
Text(normalText)
],
),
),
);
}
}
**OVERVIEW:**
**
**
- After importing the package, you can use the Html widget to pass data and configurations to it accordingly. The HTML data argument takes a string of HTML content that is parsed to display HTML content.
- Apart from that, you can specify many configurations such as callbacks for onImageTap and onLinkTap just to name a couple of them. Don't miss comments in between the code to get a clear idea.
- CustomTextStyle property is another useful feature that allows you to define formatting and styling for dom elements like headings, paragraphs, etc. as per your requirements and likings!
I hope you liked the tutorial! Stay Tuned!