WebViews in Flutter

Note: you can check out the video for this post here and the code for this post can be found here.

Presenting a web view is pretty common in mobile apps. In Flutter, this is done by using the webview_flutter package. This package is part of a larger Github repository github.com/flutter/plugins which serves as a "companion repo to the main flutter repo. It contains the source code for Flutter first-party plugins (i.e., plugins developed by the core Flutter team)."

This tutorial, will be pretty simple, we'll:

Create a basic app, with a single home screen, with a simple button to open a URL.

Create our own widget that will present a web page in a full screen.

Cover some "gotchas" when working with web views.

Fancy a Video?

Note, the video version of this post can be found at my "Flutter in 10 Minutes" video series here at fluttercrashcourse.com or my YouTube channel here.

How the WebView Widget Works

On iOS the WebView widget is backed by a WKWebView, the newer and now official UIKit control for displaying web views. On Android the WebView widget is backed by a WebView.

Step 1 of 3: Creating our Home Screen

Generating Our Project and main.dart

Generate a new Flutter project via the Flutter command line tool via: flutter create flutter_webviews. Open the generated project and replace main.dart file with the following:

Step 2 of 3: Creating home.dart

Our Home screen will show a single button that opens a URL. In this example, we'll use standard Material Design widgets too keep things simple. The screen may contain a few widgets you may not be familiar with, but the import part is understanding the _handleURLButtonPress below, which will navigate to our web view, presented by a custom widget we'll create next called WebViewContainer:

The important gotcha here is that we'll need to use a StatefulWidget because it appears that if we use a StatelessWidget, the WebView will not load properly.

We pass in a url parameter to this widget, which is used in the state of our StatefulWidget.

There are additional features of the WebView widget, offering abilities such as detecting various gestures on the web page as well as callbacks so we can be notified when the web page is created. Feel free to Ctrl/Command + Click into the WebView widget to read up on more of those features.

One More Requirement for iOS Devices

To use WebView on iOS, it's required to add an special setting in our XCode project. If you're not familiar with iOS projects, every project as a special file called Info.plist, which is a simple list of configuration settings. We can edit this file by opening <project root>/ios/Runner/Info.plist and adding the following to the file's <dict> element: