Webview in flutter - Open Local HTML file in to webview - Open URL in Webview- handle Javascript function in webview

Hello, guys today we are going to learn to load the local HTML file in a flutter.
We can achieve this by using the Webview widget

Webview widget webview_flutter 0.3.16

We have different options to load data in webview.

  • Load URL in Webview
  • Load Local Html File
  • Handle JavaScript Functions
  • Open Default Browser.

Load URL in 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

 

 

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

class WebViewURlState extends State
{
  bool isLoaded;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isLoaded=false;
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("Webview with URL"),),
      body: Stack(
        children: [
          WebView(
            initialUrl: 'https://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;
              });

            },

 

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 ago</span>
        <h2>Post One</h2>
        <p>Lorem ipsum dolor sit amet consectetur, Ducimus, repudiandae temporibus omnis illum maxime quod deserunt eligendi dolor</p>
    </div>
    <div class="card-stats">
        <div class="stat">
            <div class="value">4<sup>m</sup></div>
            <div class="type">read</div>
        </div>
        <div class="stat border">
            <div class="value">5123</div>
            <div class="type">views</div>
        </div>
        <div class="stat">
            <div class="value">32</div>
            <div class="type">comments</div>
        </div>
    </div>
</div>

 

To Read local html file we need rootBundle.
which has a method loadString() to read the 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 createState() {
    // TODO: implement createState
    return WebviewLocalState();
  }

}
class WebviewLocalState extends State
{
 WebViewController _webViewController;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("Load Html Content"),),
      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());

 }
}

 

Using JavaScript in Dart & Flutter - Handle JavaScript Functions

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 it</p>
<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 createState() {
    // TODO: implement createState
    return WebviewJsState();
  }

}
class WebviewJsState extends State
{
  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: [
               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),
    );
  }

}

 


 

 

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

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

RaisedButton(
                padding: EdgeInsets.all(12),
                child: Text("Browser",style: TextStyle(
                    color: Colors.white,fontSize: 18
                )),
                color: Colors.red,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15)
                ),
                onPressed: () {
                  _launchURL("https://rrtutors.com/");
                },
              )
              
_launchURL(url) async {

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

 

 

Dowload Large Files in Flutter Example

 

Tags: Webview, HTML, Default Browser, URL, Javascript with Flutter


Subscribe For Daily Updates