Flutter Webview - Load HTML file in to webview - Open URL in Webview- handle Javascript function in webview

Last updated Sep 27, 2021


Hello, guys today we are going to learn to load the local HTML file in a flutter. To load HTML file in flutter we will use webview widget. In this flutter webview example we will cover different ways of load html content in flutter. To work with html content we will use Webview pulgin with nullsafety webview_flutter

WebView is a widget that allows the display of web content within applications. This is a custom function that better offers the content of a page or service on Android without changing the browsing experience.

This means that it is possible to load elements of a page embedded in the tool's own interface, without having to direct the user to the browser or radically change the interface. It is a very common widget used among the developers.

Some social media uses this widget to help the user to have a better experience when he/she needs to search new content in the same app

 

We have different options to load data in webview.

  1. Load URL in Webview
  2. Load Local Html File
  3. Handle JavaScript Functions
  4. Open Default Browser

 

Download Source code

 

Flutter Webview - How do i open url in browser

 

 

How do i Load a URL in Flutter ?

To load URL in flutter we will use Webview widget, before going to load URL first we will check what is webview.

 

What Is WebView ?

Some times we want to show any web page or website or load a URL inside an application, a WebView can be displayed without the help of any browser, so, basically, it displays the content of web pages directly inside the application.

Let’s get started on how to integrate WebView inside a Flutter application

 

 

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewURL extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return WebViewURlState();
  }

}

class WebViewURlState extends State<WebViewURL>
{
  late bool isLoaded;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isLoaded=false;
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(title: Text("Webview with URL"),  backgroundColor: Colors.deepPurple,),
      body: Stack(
        children: <Widget>[
          WebView(
            initialUrl: 'http://rrtutors.com/',
            onPageFinished:(value){
              setState(() {
                isLoaded=true;
              });

            },

          ),
          (isLoaded)?Container():Center(child: CircularProgressIndicator(),)

        ],
      ),
    );
  }
}

 

Here initially we are showing the loading while loading the URL in webview.

We can check the Page load finish by onPageFinished property

onPageFinished:(value){
  setState(() {
    isLoaded=true;
  });

},
Load url in webview flutter

 

 

How to render a local HTML file with flutter dart webview

 

Let's create an assets folder inside the application and add your HTML file into this folder

  

head>
    <meta charset="UTF-8" />
    <style>
.card {
  display: grid;
  grid-template-columns: 300px;
  grid-template-rows: 210px 210px 80px;
  grid-template-areas: "image" "text" "stats";
  border-radius: 18px;
  background: white;
  box-shadow: 5px 5px 15px rgba(0,0,0,0.9);
  font-family: roboto;
  text-align: center;
}

.card-image {
  grid-area: image;

}
.card-text {
  grid-area: text;
}
.card-stats {
  grid-area: stats;

}
.card-image {
  grid-area: image;
  background: url("demo.jpg");
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  background-size: cover;
}
.card-text {
  grid-area: text;
  margin: 25px;
}
.card-text .date {
  color: rgb(255, 7, 110);
  font-size:13px;
}
.card-text p {
  color: grey;
  font-size:15px;
  font-weight: 300;
}
.card-text h2 {
  margin-top:0px;
  font-size:28px;
  font-color:#FFF;
}

.card-stats {
  grid-area: stats;
  display: grid;
 text-align: center;
 align:center;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr;
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 15px;
  background: rgb(255, 7, 110);
}
.card-stats .stat {

  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: white;
  padding:10px;
}
    style>
head>
<div class="card">
    <div class="card-image card2">
        <img class="image_class" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSqmarbIhJXnNyonPaZx-Ya4UyYFyrAox9-5n_uj1_1Hkt9ePXd" width="350px" alt="Smiley face">
    div>
    <div class="card-text">
        <span class="date">4 days agospan>
        <h2>Post Oneh2>
        <p>Lorem ipsum dolor sit amet consectetur, Ducimus, repudiandae temporibus omnis illum maxime quod deserunt eligendi dolorp>
    div>
    <div class="card-stats">
        <div class="stat">
            <div class="value">4<sup>msup>div>
            <div class="type">readdiv>
        div>
        <div class="stat border">
            <div class="value">5123div>
            <div class="type">viewsdiv>
        div>
        <div class="stat">
            <div class="value">32div>
            <div class="type">commentsdiv>
        div>
    div>
div>

To Read local html file we need rootBundle class. This class containf loadString() method which will takes path of html file.
 

 String fileHtmlContents = await rootBundle.loadString('assets/demo.html');

 

 

After read the content from html file we need to pass this data to webview, this is done by webviewcontroller.

_webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
    mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    .toString());

 

 

Now create webviewlocal.dart

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewLocal extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return WebviewLocalState();
  }

}
class WebviewLocalState extends State<WebviewLocal>
{
 late WebViewController _webViewController;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(title: Text("Load Html Content"),  backgroundColor: Colors.deepPurple,),
      body: Container(
          child: WebView(
            initialUrl: '',
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController){
              _webViewController=webViewController;
              loadAsset();
            },
          )),
    );;
  }
 loadAsset() async {
   String fileHtmlContents = await rootBundle.loadString('assets/demo.html');
   _webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
       mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
       .toString());

 }
}

 

Flutter javascript events webview

 

 

How do i handle Javascript functions in flutter?

Now we are going to handle Javascript in Dart/flutter .

Let's put your HTML file which contains JavaScript inside the assets folder

demojs.html

html>

<head>

    <meta name="viewport" content="width=device-width, initial-scale=2">

    <script type="text/javascript">
        function add(num1, num2) {
            var result = num1 + num2;
            document.getElementById("result").innerHTML
                = num1 + " + " + num2 + " = " + result;
        }
    script>
head>

<body>
<p>Enter number to check double of itp>
<p id="result">p>
body>

html>

 

webviewjavascript.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewJs extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return WebviewJsState();
  }

}
class WebviewJsState extends State<WebviewJs>
{
  late WebViewController _webViewController;
  TextEditingController _textEditingController=TextEditingController();
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(title: Text("Load Html Content"),  backgroundColor: Colors.deepPurple,),
      body: SingleChildScrollView(
        child: Container(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
               Container(
                 decoration: getBoxShadow(),
                 margin: EdgeInsets.all(8),

                 height: 400,
                 child:  WebView(
                   initialUrl: '',
                   javascriptMode: JavascriptMode.unrestricted,
                   onWebViewCreated: (WebViewController webViewController){
                     _webViewController=webViewController;
                     loadAsset();
                   },
                 ),
               ),
                Container(
                  margin: EdgeInsets.all(8),
                  color: Colors.white,
                  child: TextField(
                    textInputAction: TextInputAction.go,
                    onSubmitted: (value){
                      if(_textEditingController.text.length>0) {
                        int number=int.parse(_textEditingController.text) ;
                        _webViewController.evaluateJavascript('add($number, $number)');
                      }
                    },
                    decoration: getInoutDecoration("Enter Number"),
                    controller: _textEditingController,
                    keyboardType: TextInputType.numberWithOptions(signed: true),
                  ),
                )
              ],
            )
        ),
      ),

    );;
  }
  loadAsset() async {
    String fileHtmlContents = await rootBundle.loadString('assets/demojs.html');
    _webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
        mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());

  }

  getBoxShadow()
  {
    return BoxDecoration(

        borderRadius: BorderRadius.circular(3.0),
        border: Border.all(color: Colors.green,width: 1),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
              color: Colors.lightGreen,
              offset: Offset(1.0, 2.0),
              blurRadius: 10,
              spreadRadius: 3)
        ]);

  }
  getInoutDecoration(hint)
  {
    return InputDecoration(
      hintText: hint,
      border: InputBorder.none,
      contentPadding: EdgeInsets.all(12),
    );
  }

}

 

Flutter Javascript events webview

 

 

Open Browser

How do I open a web browser (URL) from my Flutter code?

With the  url_launcher plugin we can open URL in device browser in flutter

Flutter provides a widget to help the developer when needs to interact with a specific app outside his/her own app and for that reason, the url launcher is available.  With this tool, you will be able to interact with Google maps, write and/or read your emails, among other options without the need of closing your own app.

 

This widget can be used in iOS or Android device, it works with both OS. However, certain mobile devices may not receive all supported URL schemes as may be the case with tablets

To start the default device browser we need to add below code
Here on button tap it will open given url in browser

MaterialButton(
  padding: EdgeInsets.all(12),
  child: Text("Browser",style: TextStyle(
      color: Colors.white,fontSize: 18
  )),
  color: Colors.purpleAccent,
  shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(15)
  ),
  onPressed: () {
    _launchURL("http://rrtutors.com/site");
  },
)

 

main.dart

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html_app/webviewjavascript.dart';
import 'package:flutter_html_app/webviewlocal.dart';
import 'package:flutter_html_app/webviewone.dart';
import 'package:flutter_html_app/webviewone.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'package:url_launcher/url_launcher.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal[200],
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: Text("Webview Examples"),
        ),
        body: Container(
          margin: EdgeInsets.all(20),
          child: GridView.count(
            crossAxisCount: 2,
           children: [
             getButton(context,"Load URL",WebViewURL()),
             getButton(context,"Load Local HTML",WebviewLocal()),
             getButton(context,"JavaScript Events",WebviewJs()),
             Card(
               margin: EdgeInsets.only(top: 10,left: 10),
               child: MaterialButton(
                 height: 40,
                 padding: EdgeInsets.all(12),
                 child: Text("Browser",style: TextStyle(
                     color: Colors.red,fontSize: 18
                 )),

                 shape: RoundedRectangleBorder(
                     borderRadius: BorderRadius.circular(15)
                 ),
                 onPressed: () {
                   _launchURL("http://rrtutors.com/site");
                 },
               ),
             )
           ],
          ),
        ),
      ),
    );
  }


  getButton(context,text,widget)
  {
    return Card(
      margin: EdgeInsets.only(top: 10,left: 10),
      child: MaterialButton(
        height: 40,
        padding: EdgeInsets.all(12),
        child: Text(text,style: TextStyle(
            color: Colors.red,fontSize: 18
        )),

        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15)
        ),
        onPressed: () {
          Navigator.push(context, MaterialPageRoute(builder:(ctx){
            return widget;
          } ));
        },
      ),
    );
  }

}

_launchURL(url) async {

  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}






 

Dowload Large Files in Flutter Example

How to parse HTML tags in flutter

 

Tags: Webview, HTML, Default Browser, URL, Javascript with Flutter, Flutter Webview, Flutter Load html, Parse HTML tags


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

7396 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions