WebView Example In Flutter

In this tutorial, you will learn how to add a WebView to your Flutter application.

What Is WebView?

WebView is a Flutter Widget that allows your mobile application to display web content. This component is pre-installed on your device and should be kept up to date to ensure you have the latest security updates and other bug fixes.

Adding WebView Flutter Plugin

Before you can start using WebView widget in your Flutter app, you will need to add one more plugin to a pubspec.yaml file. There’s an official plugin for Webview in Flutter which is available here and it is made by the Flutter team. Add it to your pubspec.yaml file where all the dependencies are listed.

webview_flutter: ^1.0.7

Now that you have added the plugin to your dependencies, we will continue with the next step.

Creating WebView

Below is a basic code that you need to create a WebView object.

WebView(
        initialUrl: 'https://flutter.dev/',
        javascriptMode: JavascriptMode.unrestricted,
      )

In the code snippet above the WebView widget takes two parameters and they are:

  • initialUrl – is the URL of the web resource you that it needs to load,
  • javascriptMode – enables the WebView to run JavaScript. By default, JavaScript support is disabled, and in order to run JavaScript, we have to set JavaScriptMode to unrestricted.

Note: If you want to make sure that the WebView should be responsive and cover the entire screen then you should add an Expanded widget to its parent.

 

Complete Code Example

Below is a complete code example of how to add a WebView widget to your Flutter mobile application.

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(
      home: Body(),
    );
  }
}

class Body extends StatefulWidget {
  @override
  _BodyState createState() => _BodyState();
}

class _BodyState extends State<Body> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('InAppWebView Example'),
      ),
      body: Expanded(
        child: WebView(
          initialUrl: 'https://flutter.dev/',
          javascriptMode: JavascriptMode.unrestricted,
        ),
      ),
    );
  }
}

I hope this tutorial was helpful to you. If you are interested in Flutter and are looking for other short tutorials like this, check the Flutter tutorials page on this website. If you prefer to learn by watching video tutorials, then have a look at the Futter video tutorials page.

Happy learning and mobile app development with Flutter to you!


Leave a Reply

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