How to open URL in a browser in Flutter? (2023)

During the app development, we need to open the URL in an external web browser. In this article, we are going to learn "How to open URL in a browser in Flutter?".  We may need to launch URLs very often like app rating links, youtube links, or your own website. We have used the Flutter package which helps to open URLs easily. 

We need to add url_launcher: ^6.1.10 package in our pubspec.yaml file like the below.

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^6.1.10

 

To launch the URL in an external browser, use the below code:

 if (!await launchUrl(
      url,
      mode: LaunchMode.externalApplication,
    )) {
      throw Exception('Could not launch $url');
    }

 

NOTE:

If you target SDK 30 or above canLaunch will return false by default due to package visibility. changes: https://developer.android.com/training/basics/intents/package-visibility In the androidManifest.xml you'll need to add the following directly under <manifest>

 

<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
    </intent>
</queries>

Let's take a full example so you got an idea about how to easily open URLs in a web browser.

Full Example:

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

class Errorgram extends StatefulWidget {
  const Errorgram({Key? key}) : super(key: key);

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  final _formKey = GlobalKey<FormState>();
 
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        bottom: false,
        child: Scaffold(
            appBar: AppBar(
              automaticallyImplyLeading: false,
              centerTitle: true,
              title: Text(
                "Errorgram",
              ),
            ),
            body: Center(child: TextButton(child: Text("Open Link"),onPressed: () {
              _launchInBrowser(Uri.parse("https://errorgram.com/"));
            },),)));
  }

  Future<void> _launchInBrowser(Uri url) async {
    if (!await launchUrl(
      url,
      mode: LaunchMode.externalApplication,
    )) {
      throw Exception('Could not launch $url');
    }
  }
}

 

Output:

 

 

Conclusion:

In this article, we have learned How to open URLs in a browser in Flutter with full examples. I hope this article may help you.

 

Tags: