Create WebView App in Flutter

The webview_flutter package allows, load any webpage on your flutter app. In this tutorial you will learn flutter webview widget. So let’s get started.

Create a Project

First create a project by using IDE or flutter create commend. If you are using existing project, no problem continue the step.

 Adding Webview dependency

After creating the project. Open pubspec.yaml file and add webview_flutter package in your dependency. Then don’t forget to run pub get, then only the package will add your project. The current version is webview_flutter: 2.0.4. In feature it may change, please use the latest version.

Then, set the minSdkVersion in android/app/build.gradle.

android {
    defaultConfig {
        minSdkVersion 19
    }
}

Creating WebView

Now, create a WebView widget and set the initialUrl as your webpage URL. By default the java script will be restricted. Some times it may affect your app may not work properly. To remove this limitation use javascriptMode property. The WebView widget code is given below.

WebView(
         initialUrl: 'https://www.codewithflutter.com',
        javascriptMode: JavascriptMode.unrestricted,
       )

Adding Progress bar

To add the progress bar in our app, wrap the WebView widget as Stack Widget. Then create an isLoading boolean variable and set the default value true. WebView widget has some properties called onPageStarted, onPageFinished. In onPageStarted property set isLoading value as true as well as onPageFinished property set isLoading value as false. In the stack widget, create a circular progress indicator. The indicator is only shown when the isLoading is true otherwise it will be hidden. The code is given below,

  bool isLoading = true;
 Stack(
            children: [
              WebView(
                initialUrl: 'https://www.codewithflutter.com',
                javascriptMode: JavascriptMode.unrestricted,
                onPageStarted: (url) {
                  setState(() {
                    isLoading = true;
                  });
                },
                onPageFinished: (status) {
                  setState(() {
                    isLoading = false;
                  });
                },
                onWebViewCreated: (WebViewController controller) {
                  webView = controller;
                },
              ),
              isLoading
                  ? Center(
                      child: Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 50.0, vertical: 20.0),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(25.0)),
                      child: CircularProgressIndicator(),
                    ))
                  : Stack(),
            ],
          ),

Handling WebView back Button

Then we creating a webview controller. Under Weview widget onWebViewCreated property we giving this property.

 WebViewController webView;
.....
WebView(
...
 onWebViewCreated: (WebViewController controller) {
                  webView = controller;
                },
)

To handle webview back button wrap your scaffold widget as WillPopScope widget.

The code is given below,

 WillPopScope(
      onWillPop: () => _onBack(),
       ....
    )

When pressing the back button the _onBack() function will be called, the function checks WebView history is available or not. If history is available then the webview goes back to the previews page otherwise the app will be closed. The _onBack() function code is given below,

Future<bool> _onBack() async {
    var value = await webView.canGoBack();

    if (value) {
      await webView.goBack();
      return false;
    } else {
      return true;
    }
  }

Here the output Screenshot,

Create WebView App in Flutter
Flutter WebView App

Here the full source code of the project.

Create WebView App in Flutter
Flutter WebView with Progress bar
Create WebView App in Flutter
Flutter WebView App Demo
import 'dart:async';

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter WebView',
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool isLoading = true;

  WebViewController webView;

  Future<bool> _onBack() async {
    var value = await webView.canGoBack();

    if (value) {
      await webView.goBack();
      return false;
    } else {
      return true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => _onBack(),
      child: Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              WebView(
                initialUrl: 'https://www.codewithflutter.com',
                javascriptMode: JavascriptMode.unrestricted,
                onPageStarted: (url) {
                  setState(() {
                    isLoading = true;
                  });
                },
                onPageFinished: (status) {
                  setState(() {
                    isLoading = false;
                  });
                },
                onWebViewCreated: (WebViewController controller) {
                  webView = controller;
                },
              ),
              isLoading
                  ? Center(
                      child: Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 50.0, vertical: 20.0),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(25.0)),
                      child: CircularProgressIndicator(),
                    ))
                  : Stack(),
            ],
          ),
        ),
      ),
    );
  }
}

Related Posts,