In Flutter, How do you implement WebView?

Hey Everyone,

Today in this article we are going to learn about how to use “WebView” in flutter project.

Introduction

You may add a WebView widget to your Android or iOS Flutter app with the WebView Flutter plugin. A WKWebView supports the WebView widget on iOS, whereas a WebView supports the WebView widget on Android.

So, follow below steps to add webview in your flutter application for android and iOS both.

Step 1: Add webview flutter dependencie to pubspec.yaml file, as seen below

environment:
  sdk: ">=2.7.0 <3.0.0"
dependencies:
  flutter:
    sdk: flutter
  webview_flutter: ^0.3.0

Step 2: Open your dart file and Import webview package to your project.

import 'package:webview_flutter/webview_flutter.dart';

Step 3: Now you can used webview widget in your statefull or stateless widget.

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(
  MyApp(),
);
class MyApp extends StatelessWidget {
  WebViewController _controller;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'WebView’,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Flutter WebView"),
        ),
        body: Center(
          child: WebView(
            initialUrl: ' https://flutter.dev/',
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController) {
              _controller = webViewController;
            },
          ),
        ),
      ),
    );
  }
} 

This is basically simple webview in flutter now if you want to implement all the webview functions then follow below steps.

Step 4: Monitoring page load event.

Your app can listen to multiple page load progress events provided by the WebView widget. Three separate page load events are fired during the WebView page load cycle: onPageStarted, onProgress, and onPageFinished.

In this step, you’ll add a page load indicator to your webview. as seen below.

  • Create variable in your widget
var loadingPercentage = 0;
  • Use load function as seen below
WebView(
    initialUrl: 'https://flutter.dev',
    onPageStarted: (url) {
        setState(() {
           loadingPercentage = 0;
        });
    },
    onProgress: (progress) {
       setState(() {
          loadingPercentage = progress;
       });
   },
   onPageFinished: (url) {
      setState(() {
         loadingPercentage = 100;
      });
   },
),
if (loadingPercentage < 100)
    LinearProgressIndicator(
    value: loadingPercentage / 100.0,
),

Step 5: Used of  WebViewController

With a WebViewController, the WebView widget may be controlled programmatically.

A callback is used to make this controller available after the WebView widget has been constructed.

So first create controller in your webview.

WebViewController controller;

Now in your initstate add bellow function for used scroll stop in webview.

void initState() {
  if (Platform.isAndroid) {
    WebView.platform = SurfaceAndroidWebView();
  }
}

Now use controller as seen below.

WebView(
       initialUrl: 'https://flutter.dev',
       onWebViewCreated: (webViewController) {
        widget.controller.complete(webViewController);
       },
      onPageStarted: (url) {
        setState(() {
            loadingPercentage = 0;
        });
      },
      onProgress: (progress) {
        setState(() {
           loadingPercentage = progress;
        });
      },
      onPageFinished: (url) {
        setState(() {
           loadingPercentage = 100;
        });
   },
),
if (loadingPercentage < 100){
  LinearProgressIndicator(
     value: loadingPercentage / 100.0,
  ),
}

Step 6: How to Evaluating JavaScript

You must set the javaScriptMode property of the WebView widget to JavascriptMode.unrestricted to enable JavaScript. JavascriptMode is set to JavascriptMode.disabled by default. you can check any condition before load new WebView using javascriptmode.

Follow below code for Evaluating JavaScript.

bool goToyoutube = true;
WebView(
          initialUrl: 'https://flutter.dev',
          onWebViewCreated: (webViewController) {
            widget.controller.complete(webViewController);
          },
          onPageStarted: (url) {
            setState(() {
              loadingPercentage = 0;
            });
          },
          onProgress: (progress) {
            setState(() {
              loadingPercentage = progress;
            });
          },
          onPageFinished: (url) {
            setState(() {
              loadingPercentage = 100;
            });
          },
  navigationDelegate: (navigation) {
            final host = Uri.parse(navigation.url).host;
            if (host.contains('youtube.com')) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(
                    'Blocking navigation to $host',
                  ),
                ),
              );
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },

          javascriptMode: JavascriptMode.unrestricted,       
        ),
        if (loadingPercentage < 100)
          LinearProgressIndicator(
            value: loadingPercentage / 100.0,
          ),

Step 7: Add JavaScript Channels in WebView.

you can get message from JavaScript Chenal so if you implement JavaScript channel then you will get message from JavaScript channel and using that you can implement your code.

WebView(
          initialUrl: 'https://flutter.dev',
          onWebViewCreated: (webViewController) {
            widget.controller.complete(webViewController);
          },
          onPageStarted: (url) {
            setState(() {
              loadingPercentage = 0;
            });
          },
          onProgress: (progress) {
            setState(() {
              loadingPercentage = progress;
            });
          },
          onPageFinished: (url) {
            setState(() {
              loadingPercentage = 100;
            });
          },
          navigationDelegate: (navigation) {
            final host = Uri.parse(navigation.url).host;
            if (host.contains('youtube.com')) {
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
          javascriptMode: JavascriptMode.unrestricted,
          javascriptChannels: _createJavascriptChannels(context), 
        ),
        if (loadingPercentage < 100)
          LinearProgressIndicator(
            value: loadingPercentage / 100.0,
          ),

Now add channel like function in your code.

Set<JavascriptChannel> _createJavascriptChannels(BuildContext context) {
    return {
      JavascriptChannel(
        name: 'SnackBar',
        onMessageReceived: (message) {
          ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(content: Text(message.message)));
        },
      ),
    };
  }

So, that’s how you can use WebView in your project.
Hope you guys found something useful. If you have any doubts or questions do comment.

See you in the Next Article

Submit a Comment

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

Subscribe

Select Categories