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 load local html file in flutter.
We can achieve this by using Webview wedget

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

In this section we are loading a web url in webview

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: '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 Local Html File

Lets create assets folder inside application and add your html file in to 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());

 }
}

 


Handle JavaScript Functions

Lets put your html file which contains JavaScript inside 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

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("http://rrtutors.com/");
                },
              )
              
_launchURL(url) async {

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

 




Related Questions View All