Flutter Webview

Topics Covered

Flutter's WebView plugin facilitates the integration of HTML content within mobile apps across Android and iOS platforms, streamlining web page display without browser dependencies. This framework enables seamless app development, allowing reuse of existing web functionalities like secure payments within the app interface, eliminating the need for code duplication. While plugins like webview_flutter and flutter_inappwebview offer similar capabilities, the latter boasts richer features and comprehensive API documentation. Utilizing WebView expedites app development by embedding web functionalities, ensuring efficient user experience without browser redirections.

Setting up Flutter Webview

This requires two pieces of software: the Flutter SDK and an editor. Flutter is a free and open-source user interface software development kit. This toolkit provides its rendering engine, a comprehensive collection of ready-made widgets, unit and integration testing APIs, plugin APIs, and command-line tools for developing and compiling apps, in addition to a react-style framework.

Requirements for using Flutter Webview

Several tools must be installed on your PC before you can develop a Flutter project:

1. Flutter

This Flutter SDK is used to run and assemble Flutter applications. Go to the Flutter documentation to select the Flutter SDK for your operating system:

The links provide instructions on how to set up the Flutter SDK on your computer. Once installed, confirm that Flutter is in your global path. To verify that the Flutter SDK is set up and accessible on your computer worldwide, use the command flutter --help.

2. VS Code

VS Code is a sophisticated contemporary code editor offered to us by Microsoft. It contains an addon that can enable you to utilize Flutter from your VS Code with simplicity. Install the VS Code extension for Flutter.

3. Android Studio

You must have Android Studio installed on your computer to run and test your apps on Android. After that, we must set up the Flutter and Dart plugins:

Make sure everything is set up and operating. In the following step, we will build up a Flutter project.

Adding the webview_flutter Dependency

Following that, we will add the webview flutter dependency to our project. Add the following lines to the pubspec.yaml file in the root of your project:

Saving the pubspec.yaml file will prompt the VS Code to install the dependencies. If you are not using VS Code, use the below line in your terminal to install the webview flutter dependency: flutter pub get webview_flutter

Flutter pub provides Flutter package management commands. Flutter pub get gets packages in a Flutter project. In this case, the webview_flutter package is added to our Flutter project. Following that, we specified the minimum SDK version required by the webview flutter plugin. In your project, open android/app/build.gradle and add the following configuration code to the android defaultConfig section: minSdkVersion 19

webview_flutter is compatible with Android versions 19 and higher.

Loading a Webpage in Flutter Webview

The WebView widget generates several page load progress events that your app can listen for. Three different page load events are dismissed during the WebView page load cycle: onPageStarted, onProgress, and onPageFinished. In this step, you will put a page load indicator in place. As an added bonus, this demonstrates how to render Flutter content over the WebView content area. How to interact with the web content in a better way is further discussed in the following section.

Interacting with Web Content

WebView class is exported by webview flutter. This class opens a new web view and renders the specified webpage (through its URL) within the WebView widget. A WebViewController is supplied to the onWebViewCreated callback after the WebView is formed and may be used to control it. We need to import the webview flutter package to render the WebView widget:

The WebView widget is then rendered as follows:

This will render the website https://www.google.com in the WebView widget. The WebView widget will render https://www.google.com in the same way as a browser would. The initialUrl parameter passed to the WebView tells it which webpage to load and render.

interacting with web content

Further parameters can be sent to WebView. Let's have a look at them: (Please keep in mind that the following parameters and descriptions were taken from the WebView class library documentation.)

  • onWebView: This is a function that is called when the web view is built.
  • initialUrl: A string containing the URL of the webpage to be loaded and rendered by the WebView.
  • javascriptMode: This sets whether JavaScript is enabled in the WebView
  • javascriptChannels: The list of JavascriptChannels that JavaScript code executes in the WebView.
  • navigationDelegate: A delegate function that determines how navigation activities.
  • onPageStarted: Called when a page begins to load.
  • onPageFinished: Called when a page has completed loading.
  • onProgress: Invoked while a page is loading
  • debuggingEnabled: This property determines whether WebView debugging is enabled. It is set to false by default.
  • gestureNavigationEnabled: A Boolean value indicating whether horizontal swipe gestures will result in back-and-forth list navigation. It is set to false by default.
  • allowsInlineMediaPlayback: Determines whether iOS permits inline playback of HTML5 videos. This field is ignored on Android because it is enabled by default. Its default setting is false.

Handling Navigation Events

WebView offers your app a NavigationDelegate, which allows your program to track and manage the WebView widget's page navigation. The NavigationDelegate is called when the WebView initiates a navigation, such as when a user clicks on a link. The NavigationDelegate callback may be used to control whether the WebView navigates.

Here's a simple example of how to use navigationDelegate to access several links.

We can simply navigate back to the home screen or we can open Gmail or youtube since these cases have been handled here. We can also navigate back to the application's first screen. handling navigation events

Customizing the Appearance of Flutter Webview

Your app can load HTML files in various ways and display them in WebView. In this step, you will load a Flutter asset from the pubspec.yaml file, a file from the specified path, and a page from an HTML String. If you want to load a file from a specific path, you must include the path provider in pubspec.yaml. This is a Flutter plugin for finding frequently used filesystem locations. Run the following command from the command line: $ flutter pub add path_provider To load the asset, we must specify its path in pubspec.yaml. To add the assets to your project, follow these steps:

  • In the root folder of your project, create a new directory called assets.
  • Create a new Directory with the name www in the assets folder.
  • In the www folder, create a new directory called styles.
  • In the www folder, create a new file called index.html.
  • In the styles folder, create a new file called style.css.

Load Flutter Asset

To load the newly created asset, simply use the WebViewController to call the loadFlutterAsset method, passing the asset's path as a parameter. At the end of your code, include the following method:

Load Local File

To load a file on your device, use the WebViewController and add a method that uses the loadFile method, which takes a String containing the path to the file. First, create a file containing the HTML code. Simply add the HTML code as a String at the top of your code in the menu.dart file, just below the imports.

Load HTML String

It is fairly simple to display a page by providing an HTML string. The WebViewController has a method called loadHtmlString that accepts an HTML String as an argument. The provided HTML page will then be displayed by WebView.

WebViewController Method

When a WebView object is created, an instance of WebViewController is passed to the WebView.onWebViewCreated method. WebViewController is used to control a WebView and has various methods that we can call on its instance to perform various actions on the WebView. They are as follows:

  • canGoBack: The canGoBack function determines if any earlier URLs can be retrieved from the history list.
  • clearCache: clears all entries from the WebView’s cache
  • getScrollY: this returns the current location of the scroll bar in the y-axis of the WebView
  • getTitle: this function returns the title of the currently loaded WebView page.
  • goBack: the previous URL in the history list is retrieved again.
  • goForward: fetches the next URL in the history list from the current URL.
  • loadFile: This function loads a file into the WebView.
  • loadFlutterAsset: An asset is loaded into the WebView from the pubspec.yaml file of the project.
  • loadUrl: this function retrieves a webpage from a URL.
  • reload: Reloads the current WebView website.
  • runJavascript: executes the JavaScript code passed to it on the current web page's browser context in the WebView.
  • runJavascriptReturningResult: this function runs the JavaScript code supplied to it on the current webpage in the WebView and provides the results to the caller.
  • scrollBy: scrolls the webpage to a given x- and y-axis.

Now the question comes to how to initiate WebViewController in Flutter. To do this first declare a variable:

Then, in your build method where you are using the widget,

Now, you can use your _webViewController anywhere in your code.

Example Application

In this section, we'll put all the knowledge we gained before to work by building a straightforward Flutter webview application.

Install The Plugin

To include the Flutter webview plugin in your project, use the following command: flutter pub add webview_flutter Or you may add it manually in the pubspec.yaml file via pub.dev.

Implementation

Add webview flutter as an import to your Dart code:

Then create two files with the name web_view_container.dart and Home.dart. Now the code in the three files will look like this:

main.dart

Home.dart

web_view_container.dart

And this is the outcome: output-1

output-2

If we click on the back arrow we'll be redirected towards the home screen.

output-3

Best Practices for Using Webview

As more hybrid apps for mobile phones are created, it is critical to examine the security concerns associated with employing webview containers to display web-based information. Let's look at some best practices and pointers for creating hybrid apps that use webview containers:

  • Because there is a possibility of spoofing by a hostile third party, you must utilize HTTPS to interact with servers that are also operated in-house. Encrypting data communicated between a user's device and a website or service makes it far more difficult for attackers to intercept and read the data, preventing them from obtaining access to sensitive information.
  • With file access, the webview may read all files contained within the app, such as shared preferences, databases, configuration files, asset files, and so on. A simple url like file://path/file would suffice.
  • When connecting via HTTPS, an SSLException may arise as a result of a certificate verification problem or a man-in-the-middle assault. In any instance, it is critical to handle this exception correctly to maintain the security of the connection. This might include steps like advising the user of the failure, recording the issue, and so on. The particular handling of the SSLException will be determined by the application's requirements and features.
  • Enable safe browsing. Safe Browsing is a Google service that shows a warning page when a user attempts to access a virus website, a phishing site, or another risky web page.

Conclusion

  • WebViews are mobile components that allow HTML content to be displayed through a browser inside a mobile app.
  • We can now provide your consumers the experience of viewing your website in your application by using WebViews rather than having to recreate the entire setup and logic for a mobile application.
  • WebViews requires two pieces of software: the Flutter SDK and an editor.
  • Three separate page load events are dismissed throughout the WebView page load cycle: onPageStarted, onProgress, and onPageFinished.
  • Webviews may also be modified by loading HTML files in various ways and showing them in the WebView.
  • WebViewController is used to control a WebView and contains several methods that we may call on its instance to do various operations on the WebView.