Building a WebView in Flutter: A Step-by-Step Guide

Flutter Webview :

Flutter Webview implementation with custom view and full screen view is explained in this part of the tutorial.Using webview we can easily open websites with in the app and make transactions.

Sometimes we need to redirect to a website and fetch details from the site and update our app using java scripts when we implement third party payment gateways where there no SDK available.

Webview can also be embedded into the screen and can be loaded with websites just like a image view or any other widget by specifying the dimensions required.

In this tutorial we can see different ways of loading a webview like custom webview, full screen webview and more options available.

Providing the detailed video code for flutter webview integration that can guide you through implementation for both android and iOS devices.

 

Flutter webview video tutorial :

Watch this video tutorial for further insights into implementing WebView.

 

Project Structure :

This image illustrates the project structure of the WebView application implementation.

flutter webview

 

pubspec.yaml :

Add flutter_webview_plugin also make sure to add the latest version to avoid code level issues.

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  flutter_webview_plugin: 0.3.11

 

 

main.dart :

Add user agent

const androidUserAgent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36';

 


Provide the website to be opened in browser i am providing the google.com you may change it accordingly.

String weburl = 'https://www.google.com/';

 

 

Initialize the project with void main() and consider the default class MyApp()

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

 

 

Create a object for flutterWebviewPlugin

final flutterWebViewPlugin = FlutterWebviewPlugin();

 

 

Declare routes in MaterialApp()

routes: {
  '/': (_) => const MyHomePage(title: 'Flutter WebView'),
  '/widget': (_) {
    // Add widget route implementation here
  },
},

 

 

return WebviewScaffold

return WebviewScaffold(
  url: weburl, // Add website here
  mediaPlaybackRequiresUserGesture: false,
  appBar: AppBar(
    title: const Text('Widget WebView'),
  ),
);

 

 

Custom Webview :

We try to open a website with custom screen design by providing width

ElevatedButton(
  onPressed: () {
    flutterWebViewPlugin.launch(
      weburl,
      rect: Rect.fromLTWH(
          0.0, 0.0, MediaQuery.of(context).size.width, 600.0),
      userAgent: androidUserAgent,
    );
  },
  child: const Text('Open Custom WebView'),
),

 



Full Screen Webview :

Open a website in full screen when a button is pressed and will return back after closing webview.

ElevatedButton(
  onPressed: () {
    flutterWebViewPlugin.launch(weburl);
  },
  child: const Text('Open Website in Fullscreen'),
),

 

 

Add a floating action button to cancel webview

floatingActionButton: FloatingActionButton(
  onPressed: () {
    flutterWebViewPlugin.close();
  },
  tooltip: 'Close WebView',
  child: Icon(Icons.close),
  backgroundColor: Colors.red,
),

 

 

Flutter webview full code :

Here’s the complete source code for implementing a WebView.

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

const androidUserAgent =
    'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36';

String weburl = 'https://www.google.com/';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final flutterWebViewPlugin = FlutterWebviewPlugin();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter WebView',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/': (_) => const MyHomePage(title: 'Flutter WebView'),
        '/widget': (_) {
          return WebviewScaffold(
            url: weburl,   // Add website here
            mediaPlaybackRequiresUserGesture: false,
            appBar: AppBar(
              title: const Text('Widget WebView'),
            ),
          );
        },
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  // Instance of WebView plugin
  final flutterWebViewPlugin = FlutterWebviewPlugin();

  final _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: const Text('Webview'),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(
              onPressed: () {
                flutterWebViewPlugin.launch(
                  weburl,
                  rect: Rect.fromLTWH(
                      0.0, 0.0, MediaQuery.of(context).size.width, 600.0),
                  userAgent: androidUserAgent,
                );
              },
              child: const Text('Open Custom Webview'),
            ),
            RaisedButton(
              onPressed: () {
                flutterWebViewPlugin.launch(weburl);
              },
              child: const Text('Open Website in Fullscreen'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          flutterWebViewPlugin.close();
        },
        tooltip: 'Close WebView',
        child: Icon(Icons.close),
        backgroundColor: Colors.red,
      ),
    );
  }
}

 

 

Flutter webview output :

This screen depicts the usage of flutter webview

flutter webview flutter webview

If you are having any query on this tutorial on webview do let us know in comment section below.And if you like this tutorial do like, share this tutorial for more interesting tutorial.

Show Buttons
Hide Buttons
Read previous post:
Flutter BLoC Pattern Implementation

  Flutter BLoC : Flutter BLoC (Business Logic Component) Implementation is the one of the architectural way to perform to...

Close