free geoip
58

Open External URLs in Dart with Android Studio

If you’re building a Flutter app using Dart in Android Studio and need to open external URLs, this guide will…

If you’re building a Flutter app using Dart in Android Studio and need to open external URLs, this guide will show you the most efficient way to do it. Whether you’re linking to a website, launching a browser from your app, or directing users to external content, Dart makes this simple with the help of the url_launcher package.

Open External URLs in Dart

We’ll cover how to integrate this plugin, request permissions, and write complete code to launch external URLs from a Flutter app. You don’t need any advanced knowledge—just basic familiarity with Flutter and Dart.

Step 1: Add Dependency

Open your pubspec.yaml and add the url_launcher plugin:

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^6.2.5

Run flutter pub get to install the package.

Step 2: Configure Android (Android Studio)

In android/app/src/main/AndroidManifest.xml, add the following permission:

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

Also, make sure the minimum SDK version is at least 19 in android/app/build.gradle:

defaultConfig {
    minSdkVersion 19
}

Step 3: Create a Dart Class to Launch URL

File: url_launcher_service.dart

import 'package:url_launcher/url_launcher.dart';

class UrlLauncherService {
  Future<void> openUrl(String url) async {
    final Uri uri = Uri.parse(url);
    if (!await launchUrl(uri, mode: LaunchMode.externalApplication)) {
      throw Exception('Could not launch $url');
    }
  }
}

Step 4: Use It in Your Widget

File: main.dart

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

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

class MyApp extends StatelessWidget {
  final UrlLauncherService _launcher = UrlLauncherService();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Open URL in Dart")),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              _launcher.openUrl("https://www.example.com");
            },
            child: Text("Open External URL"),
          ),
        ),
      ),
    );
  }
}

This example uses the externalApplication mode to ensure the URL is opened in the device’s default browser, giving users a smoother experience.

Extra Tips

  • Always validate URLs before launching.
  • Handle exceptions gracefully to improve UX.
  • Test on both Android and iOS devices.

For more advanced usage and documentation, visit the official Flutter package site: url_launcher | pub.dev

rysasahrial

Leave a Reply

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