Open URLs in Flutter Using url_launcher with GetX Controller Binding


The url_launcher package is essential for Flutter developers who need to open links, dial phone numbers, send SMS, or compose emails from their apps. This guide will walk you through using url_launcher with GetX to create a clean and structured implementation.


Prerequisites

  1. Flutter SDK: Make sure Flutter is installed.
  2. GetX Package: Install get for state management.
  3. url_launcher: Add the package to your pubspec.yaml file.
 dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  url_launcher: ^6.1.10

Run flutter pub get to install the packages.


Step 1: Setting up the Controller

We'll create a UrlController to handle launching URLs using the url_launcher package.

url_controller.dart

 import 'package:get/get.dart';
 import 'package:url_launcher/url_launcher.dart';

class UrlController extends GetxController {
  // Method to open a URL
  Future launchUrl(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  // Method to dial a phone number
  Future dialNumber(String phoneNumber) async {
    final url = 'tel:$phoneNumber';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not dial $phoneNumber';
    }
  }

  // Method to send SMS
  Future sendSms(String phoneNumber) async {
    final url = 'sms:$phoneNumber';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not send SMS to $phoneNumber';
    }
  }

  // Method to compose email
  Future composeEmail(String email) async {
    final url = 'mailto:$email';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not compose email to $email';
     }
   }
 }

In this controller:

  • launchUrl: Opens a URL in the default browser.
  • dialNumber: Dials a phone number using the phone's dialer.
  • sendSms: Opens the SMS app with the specified number.
  • composeEmail: Opens the email client with a recipient pre-filled.

Step 2: Setting up the View

The view will allow users to input various types of data and trigger different actions by calling the appropriate controller methods.

url_view.dart

 import 'package:flutter/material.dart';
 import 'package:get/get.dart';
 import 'url_controller.dart';

 class UrlView extends GetView {
  final TextEditingController urlController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController emailController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('URL Launcher Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: urlController,
              decoration: InputDecoration(labelText: 'Enter URL'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                controller.launchUrl(urlController.text);
              },
              child: const Text("Open URL"),
            ),
            const SizedBox(height: 20),
            TextField(
              controller: phoneController,
              decoration: InputDecoration(labelText: 'Enter Phone Number'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                controller.dialNumber(phoneController.text);
              },
              child: const Text("Dial Phone Number"),
            ),
            const SizedBox(height: 20),
            TextField(
              controller: emailController,
              decoration: InputDecoration(labelText: 'Enter Email Address'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                controller.composeEmail(emailController.text);
              },
              child: const Text("Compose Email"),
            ),
          ],
        ),
      ),
     );
   }
 }

In this view:

  • TextFields: Allow users to enter a URL, phone number, or email address.
  • Buttons: Trigger the appropriate action using the UrlController methods.

Step 3: Setting up the Binding

To inject UrlController into the view, we’ll create a binding.

url_binding.dart

 import 'package:get/get.dart';
 import 'url_controller.dart';

 class UrlBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => UrlController());
   }
 }

This binding ensures the UrlController is created when needed, keeping the app memory-efficient.


Step 4: Running the App

Finally, update main.dart to configure the binding and routing.

main.dart

 import 'package:flutter/material.dart';
 import 'package:get/get.dart';
 import 'url_view.dart';
 import 'url_binding.dart';

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

 class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/',
      getPages: [
        GetPage(
          name: '/',
          page: () => UrlView(),
          binding: UrlBinding(),
        ),
      ],
      title: 'URL Launcher Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
    );
   }
 }

Wrapping Up

This code demonstrates how to:

  1. Open URLs, dial phone numbers, send SMS, and compose emails using url_launcher.
  2. Use GetX for controller binding, creating a clean and scalable architecture.
  3. Handle various launch actions from a single view with minimal code.

The combination of url_launcher and GetX provides a robust and efficient approach to managing URL actions in a Flutter app. Get started today and give your users a more dynamic experience!