Home > database >  I want to show the exact text from html file with the formatting present in Flutter
I want to show the exact text from html file with the formatting present in Flutter

Time:04-21

I am fetching data from API in Flutter and want to show it's contents. How should I show contents of a field which has html tags in it. Like, this is a data that I am getting -

{"id":509,"topic_name":"HTML testing","description":"<p>E EJ <em> jn ajsf</em><strong><em>ajs nfjnsa </em></strong></p>","status":true,"is_deleted":false,"position":1,"chapter":28,"bookmark_status":false,"is_redeemed":false,"images":[],"videos":[],"files":[],"iframes":[]}

As you can see in the description field, I am getting a string which has formatting in HTML style. How should I show this in my Flutter App inside Text widget?

I am currently using it like this -

Text(
   HtmlCharacterEntities.decode(widget.dataList[widget.index].description!),
   style: TextStyle(
       fontSize: bodyText2Size - 1,
       fontWeight: FontWeight.w400,
       color: secondaryTextColor,
       height: 1.5,
   ),

),

And I am not able to use flutter_html package, as my flutter_svg and flutter_html versions are not resolving with each other.

CodePudding user response:

You can use flutter_html package for render html in your widget.

Widget html = Html(
data: """
<h1>Table support:</h1>
<table>
<colgroup>
<col width="50%" />
<col span="2" width="25%" />
</colgroup>
<thead>
<tr><th>One</th><th>Two</th><th>Three</th></tr>
</thead>
<tbody>
<tr>
<td rowspan='2'>Rowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan</td><td>Data</td><td>Data</td>
</tr>
<tr>
<td colspan="2"><img alt='Google' src='https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png' /></td>
</tr>
</tbody>
<tfoot>
<tr><td>fData</td><td>fData</td><td>fData</td></tr>
</tfoot>
</table>""",
style: {
  // tables will have the below background color
  "table": Style(
    backgroundColor: Color.fromARGB(0x50, 0xee, 0xee, 0xee),
  ),
  // some other granular customizations are also possible
  "tr": Style(
    border: Border(bottom: BorderSide(color: Colors.grey)),
  ),
  "th": Style(
    padding: EdgeInsets.all(6),
    backgroundColor: Colors.grey,
  ),
  "td": Style(
    padding: EdgeInsets.all(6),
    alignment: Alignment.topLeft,
  ),
  // text that renders h1 elements will be red
  "h1": Style(color: Colors.red),
 }
);

CodePudding user response:

You can use this function.

String removeAllHtmlTags(String htmlText) {
     RegExp exp = RegExp(r"<[^>]*>", multiLine: true, caseSensitive: true);

     return htmlText.replaceAll(exp, '');

}

  • Related