How to open stuff outside the flutter app?

Reading time: 2 minutes

Sometimes in our apps, we have information that needs to be handled outside of our app. It can be some communication way, like phone calls or writing emails. The most used case will be the opening of a website in the browser. I find the library in the bottom very easy to use, and want to show a few examples of how to use it.

First we need to get it:

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^5.5.2

Next, I like to write utility classes that help to avoid code duplication and make it easier to use in general. This example you can actually just copy and use at it is:

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

class LaunchUtils {
  static performPhoneCall(BuildContext context, String tel) async {
    var url = "tel:${tel.trim().replaceAll(" ", "")}";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      showError(context, "Can't call $tel");
    }
  }

  static sendEmail(BuildContext context, String mail) async {
    var url = "mailto:${mail.trim().replaceAll(" ", "")}";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      showError(context, "Can't mail $mail");
    }
  }

  static openWeb(BuildContext context, String website) async {
    var url = "$website";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      showError(context, "Can't open page $website");
    }
  }

  static showError(BuildContext context, String msg) {
    Scaffold.of(context)
      ..hideCurrentSnackBar()
      ..showSnackBar(
        SnackBar(
          content: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [Text(msg), Icon(Icons.error)],
          ),
          backgroundColor: Theme.of(context).errorColor,
        ),
      );
  }
}

This is how we can use it, web as example:

import 'package:flutter/material.dart';
import 'package:flutter_examples/example/utils/launcher_utils.dart';

class LauncherExamplePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.blueAccent,
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              InkWell(
                child: Text("https://cosmbit.com", style: TextStyle(color: Colors.white, fontSize: 26.0)),
                onTap: () {
                  LaunchUtils.openWeb(context, "https://cosmbit.com");
                },
              )
            ],
          ),
        ));
  }
}

1 thought on “How to open stuff outside the flutter app?”

Leave a Reply

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