How to Convert/Show HTML as Widget in Flutter

In this example, you will learn to convert or show HTML markup as a widget in Flutter. We have used flutter_widget_from_html flutter package to convert HTML to the widget, and it also caches the images.

Read this also: How to Remove HTML tags from String in Flutter/Dart

First, install flutter_widget_from_html Flutter package by adding the following line in your pubspec.yaml file. This package cached the network image in <IMG> tag.

dependencies:
  flutter:
    sdk: flutter
  flutter_widget_from_html: ^0.3.3+3

Now see the code and do the same:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';

class HTMLtoWidget extends StatelessWidget{

    final String htmlcode = """
     <h1>H1 Title</h1>
     <h2>H2 Title</h2>
        <p>A paragraph with <strong>bold</strong> and <u>underline</u> text.</p>
        <ol>
          <li>List 1</li>
          <li>List 2<ul>
              <li>List 2.1 (nested)</li>
              <li>List 2.2</li>
             </ul>
          </li>
          <li>Three</li>
        </ol>
     <a href="https://www.hellohpc.cdom">Link to HelloHPC.com</a>
     <img src='https://www.hellohpc.com/wp-content/uploads/2020/05/flutter.png'/>
    """;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar:AppBar(title: Text("HTML to Widget")),
        body:Container( 
            child: Card( 

              child:HtmlWidget( //to show HTML as widget.
                htmlcode,
                webView: true,
                bodyPadding: EdgeInsets.all(10),
                //body padding (Optional)
                baseUrl: Uri.parse("https://www.hellohpc.com"),
                //baseURl (optional)
                onTapUrl:(url){
                  print("Clicked url is $url");
                  //by default it shows app to open url.
                  //or you can do it in your own way
                }
              ),
            )

        ),
    );
  }

}

In this way, you can convert or show HTML as a widget in Flutter App.

No any Comments on this Article


Please Wait...