Load Local html file into WebView in Flutter. Call JS function from Flutter.

By | May 25, 2019

The first thing you need is the webview plugin itself and you can get it from the below link
https://pub.dev/packages/webview_flutter

WebView Flutter


Watch Video Tutorial


Sample HTML file

Below is the sameple HTML code that we are going to load into the webview
I have saved this file under a folder named “files” in the root of the project.
For the App to access the directory, make sure to add the folder in the [ubspec.yaml file.]

After opening the pubspec.yaml file and go to the assets section, there add ths folder “files”.


  # To add assets to your application, add an assets section, like this:
  assets:
   - images/
   - json/
   - videos/
   - files/

HTML File

<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>Hello from Flutter</p>
    <p id="result"></p>
</body>

</html>

Next we will create the UI by adding the webview.

Complete code

Below is the full source code. Here we are loading the webview with empty Url at first and when the webview returns with the ‘onWebViewCreated’ callback, we will initialize the WebViewController which is then used to load the Local HTML file. The webViewController instance is also used to call javascript functions using evaluateJavascript method.
Here we are calling the ‘add’ function in the local html file which adds two numbers and show in the Webview.

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

class WebViewTest extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _WebViewTestState();
  }
}

class _WebViewTestState extends State<WebViewTest> {
  //
  WebViewController _webViewController;
  String filePath = 'files/test.html';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Webview Demo')),
      body: WebView(
        initialUrl: '',
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _webViewController = webViewController;
          _loadHtmlFromAssets();
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          _webViewController.evaluateJavascript('add(10, 10)');
        },
      ),
    );
  }

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

  

Leave a Reply

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