How to use URL launcher in Flutter with Example Code



Flutter, a popular UI toolkit, has opened doors to seamless cross-platform app development. As developers increasingly adopt this powerful framework, one essential feature they often seek is launching URLs. In this tutorial, we’ll explore how to use the URL Launcher package in Flutter with clear examples, guiding you step-by-step to enhance your app’s functionality.

Integrating the URL Launcher Package

First, ensure you’ve installed the Flutter SDK and set up your preferred IDE. To begin, navigate to your pubspec.yaml file in your project’s root directory. Add the following dependency to your file:

dependencies:
  url_launcher: ^6.0.12

This code snippet includes the latest version of the URL Launcher package as of September 2021. It’s always a good idea to check the official package page for the most recent version.

Importing the Package

Now that the dependency is in place, open the Dart file where you want to implement URL Launcher functionality. Add the following import statement at the beginning of your file:

import 'package:url_launcher/url_launcher.dart';

Creating a Launch URL Function

With the package imported, let’s create a function that will launch a URL using the URL Launcher. Consider the following example:

Future<void> launchURL(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

In this code snippet, we define an asynchronous function called launchURL() that accepts a URL as a parameter. The function checks if the URL can be launched using the canLaunch() method. If it’s valid, the launch() method opens the URL; otherwise, an error is thrown.

Incorporating URL Launcher into Your App

It’s time to put our launchURL() function to work. Let’s create a simple Flutter app that contains a button to launch a specific URL. Here’s an example:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('URL Launcher Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () => launchURL('https://www.example.com'),
            child: Text('Launch URL'),
          ),
        ),
      ),
    );
  }

  Future<void> launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}

In this example, we’ve created a basic Flutter app with a single button that, when pressed, launches the specified URL using our launchURL() function. You can replace ‘https://www.example.com’ with any valid URL of your choice.

Launching Different URL Types

URL Launcher isn’t limited to opening web pages. It can also handle various other URL types, such as mailto, tel, and SMS. Here are examples of how to use each:

launchURL('mailto:[email protected]?subject=Hello&body=Nice%20to%20meet%20you');
launchURL('tel:+1234567890');
launchURL('sms:+1234567890');

Customizing URL Launch Behavior

URL Launcher provides additional customization options, such as opening a URL in the same window or a new window, and launching native apps. Here’s how to implement these features:

Opening a URL in the same window:

await launch(url, forceSafariVC: true, forceWebView: true);

Opening a URL in a new window:

await launch(url, forceSafariVC: false, forceWebView: false);

Launching a native app:

await launch(url, universalLinksOnly: true);

Keep in mind that some of these options are platform-specific, and you might need to adjust your code accordingly.

Handling Platform-Specific Behavior

When dealing with platform-specific behavior, it’s essential to account for differences between Android and iOS. For instance, on Android, you can customize the behavior of the launched URL with additional flags:

await launch(
  url,
  enableJavaScript: true,
  android: AndroidIntentFallback(
    componentName: 'com.example.android.intent_fallback_example',
    package: 'com.example',
    data: 'example://example',
    flags: <int>[Flag.FLAG_ACTIVITY_NEW_TASK],
  ),
);

In this example, we pass an AndroidIntentFallback object to the launch() function, specifying the package name, component name, data, and flags. This allows us to customize the launched activity on Android.

Enhancing Accessibility with URL Launcher

For a more accessible app, you can implement a fallback mechanism in case the user’s device doesn’t support URL Launcher. Consider the following example:

Future<void> launchURL(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('URL Launcher Error'),
          content: Text('Could not launch $url'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('Close'),
            ),
          ],
        );
      },
    );
  }
}

In this example, we’ve modified the launchURL() function to display an error dialog when the URL cannot be launched. This provides better feedback to users when the URL Launcher is unavailable.

Wrapping Up

URL Launcher is a powerful tool that allows you to enhance your Flutter app with the ability to launch URLs and handle various URL types. By incorporating the package into your project, you can open web pages, send emails, make calls, and send SMS messages, all while providing a seamless user experience. With these examples and tips, you’re now ready to integrate URL Launcher into your Flutter app with ease. Happy coding!

Leave a Comment