How to Open Web Browsers in Flutter

There are many ways to open web browsers in Flutter. You can open a URL, show a webview, or use an in-app browser. This post will teach you how to do all of these and help you pick the right package.

Open Web Browsers Using the URL Launcher in Flutter

We will start with opening a URL with the click of a button. To do this, we need to install the Url Launcher package

Install the URL Launcher Package

To install the Url Launcher package into our project. We can execute the following command inside our project:

flutter pub add url_launcher

After executing the command, check your pubspec.yaml file for the added dependencies. You should see the Url Launcher package included in the dependencies section, like this:

dependencies:
  url_launcher: ^6.2.6

Implement the URL Launcher Package

After having installed the package, we can now continue with the implementation.

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

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () => launchUrl(Uri.parse('https://onlyflutter.com/')),
            child: const Text('Open Browser'),
          ),
        ),
      ),
    );
  }
}

The implementation itself is pretty straightforward. Inside our MyApp widget, we return our MaterialApp widget that has an ElevatedButton widget. When we click the button it will call the launchUrl function. The launchUrl function is from the Url Launcher package, so we import the package at the top.

The launchUrl function takes a url parameter that is of the type Uri. Inside the function, we provide the URL we want to open. Afterward, we can run our application.

If you want to ensure that the URL can be launched you can create a custom function that will catch any errors.

Future<void> _launchUrl(Uri url) async {
  try {
    await launchUrl(url);
  } catch (error) {
    print(error);
  }
}

In the above example, we used a try-catch to catch any possible error. If you want to test it out, ensure you are calling the _launchUrl function instead of the launchUrl function when pressing the button.

You can also use the package’s canLaunchUrl function. This function checks if the user’s device has any URL handlers available, such as the Chrome browser.

Future<void> _launchUrl(Uri url) async =>
    canLaunchUrl(url).then((bool canLaunch) async {
      if (canLaunch) {
        await launchUrl(url);
      } else {
        print('Cannot launch URL');
      }
    });

However, this approach requires additional configurations in either the AndroidManifest.xml for Android or Info.plist for iOS. You can read more about it here, or leave a comment if you need any help.

Open Web Browsers using the WebView Flutter package

Instead of directly launching the URL in the browser we can also use a webview. The webview allows us to open the URL, but the browser view will be embedded inside the application. This approach ensures the user will not leave the application when using the Web Browser.

Install the WebView Flutter Package

Instead of implementing our own webview, we can use the Webview Flutter package. The package can be installed by executing the following command:

flutter pub add webview_flutter

As before, ensure the package is installed by checking the dependencies inside your project’s pubspec.yaml file.

dependencies:
  webview_flutter: ^4.7.0

Implement the WebView Flutter Package

To use the webview we can use the package’s WebViewWidget. Let us have a look at the following code.

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

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

class MyApp extends StatelessWidget {
  MyApp({super.key});

  final controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..loadRequest(Uri.parse('https://onlyflutter.com'));

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Padding(
          padding: const EdgeInsets.only(top: kToolbarHeight),
          child: WebViewWidget(controller: controller),
        ),
      ),
    );
  }
}

In this code, we created a controller variable to store a WebViewController instance. We are using the cascade operator to already assign some values to it. We ensure that the webview is allowed to use Javascript and we use loadRequest to load our URL.

Inside the build function we return the WebViewWidget which takes a controller. We wrapped the widget with padding to ensure that the toolbar is not obstructing the website.

Open Web Browsers Using the Flutter In App Webview package

If the webview is not sufficient and you want to allow the user to freely navigate to other websites while not being able to leave the application. You can choose to use the Flutter In App Webview package.

Install the In App Webview Package

First, we need to install the package by executing the following command:

flutter pub add flutter_inappwebview

Ensure the package is installed correctly by checking the dependencies in your pubspec.yaml file once more.

dependencies:
  flutter_inappwebview: ^6.0.0

Implement the In App Webview Package

With the package installed, we can move on with the implementation. The implementation is very similar to the Url Launcher implementation, let us have a look at the code.

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

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

class MyApp extends StatelessWidget {
  MyApp({super.key});

  final settings = InAppBrowserClassSettings(
    browserSettings: InAppBrowserSettings(hideUrlBar: false),
    webViewSettings: InAppWebViewSettings(javaScriptEnabled: true),
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () => InAppBrowser().openUrlRequest(
              urlRequest: URLRequest(url: WebUri('https://onlyflutter.com')),
              settings: settings,
            ),
            child: const Text('Open Browser'),
          ),
        ),
      ),
    );
  }
}

Once again inside our build function, we have a centered button that will launch the in-app web browser. Therefore we have to call the openUrlRequest function which can only be called on an InAppBrowser instance. The openUrlRequest function takes a url of type WebUri, and settings.

The settings require an instance of the InAppBrowserClassSettings. In this case, we ensure that the URL bar is not hidden and that JavaScript is enabled. These settings are not mandatory since they are the default values. However, I wanted to show you how it could be done.

How to Choose the Right Package for Your Flutter Project?

In each section, we have already discussed the reasons for switching to another package. Below, you will find additional reasons for using each package.

  • Url Launcher: Use this package when you want to open a URL in the user’s device browser. It offers less control because the user is free to navigate using their default browser.
  • Webview Flutter: The Webview Flutter package is ideal when you want to embed a URL inside your application. The user will not be able to navigate freely around and can only stay on the current website. However, the user will be able to follow all the redirect links in the embedded website.
  • Flutter In App Webview: The In App Webview package is the most advanced one. It allows you to create an in-app web browser where the user can freely navigate to any website, however they will stay inside your application.

Conclusion

As you have seen Flutter has many packages that can be used to open browsers in your application. We covered the basics of all these packages, so you should now know which package to use in each scenario. Keep in mind that in this post we only went over the browser possibilities of these packages. The packages themselves offer much more than just that!

Tijn van den Eijnde
Tijn van den Eijnde
Articles: 37

Leave a Reply

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