How to Create a Progress Indicator for WebView in Flutter

When you are using webview to show some web pages inside your mobile app you may always want to show progress indicator at the time of loading. In this blog post let’s see how to add a webview with progress indicator in flutter.

If you don’t know how to add a webview in flutter, then please do check out my previous blog post here.

First you need to add webview flutter dependency in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  webview_flutter: 1.0.1

This flutter webview with progress bar example uses widgets such as IndexedStack and CircularProgressIndicator. The IndexedStack widget helps to switch widgets according to the index. We also make use of onPageStarted and onPageFinished attributes of webview. Using state management we change the value of index when the page started to load and also when the page loading is finished.

Go through the complete example given below.

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


void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Webview with Progress Indicator Example',
      home: WebviewExample(),
    );
  }
}

class WebviewExample extends StatefulWidget {
  WebviewExample({Key key}) : super(key: key);

  @override
  _WebviewExampleState createState() => _WebviewExampleState();
}

class _WebviewExampleState extends State<WebviewExample> {

  num position = 1 ;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
        title: Text('Webview with ProgressBar')),
      body: IndexedStack(
      index: position,
      children: <Widget>[
 
      WebView(
        initialUrl: 'https://google.com',
        javascriptMode: JavascriptMode.unrestricted,
        onPageStarted: (value){setState(() {
                          position = 1;
                        });},
        onPageFinished: (value){setState(() {
                          position = 0;
                        });},
        ),
 
       Container(
        child: Center(
          child: CircularProgressIndicator()),
        ),
        
      ])
  );
  }
}

Following is the output of this flutter tutorial.

I hope this flutter tutorial of webview with progress will help you. Stay tuned for more tutorials.

1 thought on “How to Create a Progress Indicator for WebView in Flutter”

  1. Pingback: How to Add Raw HTML in Flutter Webview – Flutter For You

Leave a Comment

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