Posted in Dart Flutter

Flutter – How to Convert/Show HTML as Widget with Image Caching

Flutter – How to Convert/Show HTML as Widget with Image Caching Posted on May 15, 20201 Comment
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Do you want to show HTML code as a widget with network image caching included with <img> tag, then have a look at the example below and learn how to do it.

html to widget

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 and show HTML code as Flutter widget with caching of Network image in <IMG> tag.

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *