Volver a la página principal
viernes 22 noviembre 2024
30

Cómo usar url_launcher en Flutter

El paquete url_launcher permite abrir enlaces web, aplicaciones de correo, mapas o números de teléfono directamente desde tu aplicación Flutter. Es una herramienta esencial para integrar interacciones externas dentro de tu app.

¿Qué es url_launcher y para qué se utiliza?

url_launcher es un paquete que facilita la apertura de URLs en el navegador, llamadas telefónicas, correos electrónicos y aplicaciones compatibles en dispositivos Android e iOS. Este paquete es útil para redirigir a los usuarios a sitios web, contactar soporte o realizar acciones específicas con otras aplicaciones.

Instalación y configuración

Paso 1: Agregar el paquete

Añade url_launcher en tu archivo pubspec.yaml:

dependencies:
  url_launcher: ^6.1.10

Ejecuta el siguiente comando para instalar las dependencias:

flutter pub get

Paso 2: Configuración adicional

Android

Modifica el archivo AndroidManifest.xml para permitir el acceso a internet:

<uses-permission android:name="android.permission.INTERNET"/>

iOS

Asegúrate de que el archivo Info.plist incluya las claves necesarias para abrir URLs:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>https</string>
  <string>http</string>
  <string>tel</string>
  <string>mailto</string>
</array>

Uso básico de url_launcher

1. Importar el paquete:

import 'package:url_launcher/url_launcher.dart';

2. Abrir un enlace web:

Future<void> openUrl() async {
     final Uri url = Uri.parse('https://flutter.dev');

     if (await canLaunchUrl(url)) {
       await launchUrl(url);
     } else {
       throw 'No se pudo abrir $url';
     }
   }

3. Hacer una llamada telefónica:

Future<void> makePhoneCall() async {
     final Uri phoneUrl = Uri.parse('tel:+1234567890');

     if (await canLaunchUrl(phoneUrl)) {
       await launchUrl(phoneUrl);
     } else {
       throw 'No se pudo realizar la llamada';
     }
   }

4. Enviar un correo electrónico:

Future<void> sendEmail() async {
     final Uri emailUrl = Uri(
       scheme: 'mailto',
       path: 'soporte@example.com',
       query: 'subject=Soporte&body=Hola, necesito ayuda',
     );

     if (await canLaunchUrl(emailUrl)) {
       await launchUrl(emailUrl);
     } else {
       throw 'No se pudo abrir el correo';
     }
   }

Métodos principales de url_launcher

Método Descripción
canLaunchUrl() Verifica si se puede abrir un URL en el dispositivo.
launchUrl() Abre un URL en el navegador o aplicación correspondiente.
launchUrlMode Define cómo se debe abrir un enlace (por ejemplo, en la app o navegador).

Ejemplo completo: Abrir enlaces desde un botón

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

class UrlLauncherExample extends StatelessWidget {
  final Uri url = Uri.parse('https://flutter.dev');

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Ejemplo de url_launcher')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              if (await canLaunchUrl(url)) {
                await launchUrl(url);
              } else {
                throw 'No se pudo abrir el enlace';
              }
            },
            child: Text('Abrir Flutter.dev'),
          ),
        ),
      ),
    );
  }
}

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

Referencias oficiales

Para más configuraciones avanzadas y documentación completa, visita la documentación oficial de url_launcher.

Etiquetas:
dart flutter
Compartir:
Creado por:
Author photo

Jorge García

Fullstack developer