In this post, we will explore how to open a web browser (URL) from your Flutter code. This is a common requirement in many apps where you need to redirect the user to an external website.
TL;DR
This can now be implemented as Plugin with simple usage like this:
final Uri url = Uri.parse('https://flutter.dev'); if (!await launchUrl(url)) { throw Exception('Could not launch $_url'); }
Full example
To open a URL from your Flutter code, you will need to add the url_launcher
package to your project. You can do this by adding the following line to your pubspec.yaml
dependencies: url_launcher: ^6.1.11
Then in your Dart code, you will need to import the package and use it like this:
import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(new Scaffold( body: new Center( child: new RaisedButton( onPressed: _launchURL, child: new Text('Show Flutter homepage'), ), ), )); } _launchURL() async { final Uri url = Uri.parse('https://flutter.dev'); if (!await launchUrl(url)) { throw Exception('Could not launch $_url'); } }
Special Characters
If the URL value contains spaces or other values that are not allowed in URLs, you will need to use Uri.encodeFull(urlString)
or Uri.encodeComponent(urlString)
and pass the resulting value instead.
final Uri url = Uri.parse('https://example.com/path with spaces');
You can use either of these methods to encode the URL. The difference between them is that Uri.encodeFull
will encode the whole string, while Uri.encodeComponent
will only encode the individual components.
Changes in Flutter 3 and above
In Flutter 3 and above, there are some changes to how you can launch URLs. You will need to add a queries
section to your AndroidManifest.xml file like this:
Then you can use the following code to launch a URL:
const uri = Uri.parse("https://flutter.io"); if (await canLaunchUrl(uri)){ await launchUrl(uri); } else { // can't launch url }
launchUrl with mode parameter
The launchUrl
function has a mode
parameter that you can use to control how the URL is launched. You can pass in one of the following values:
LaunchMode.platformDefault
: Leaves the decision of how to launch the URL to the platform implementation.LaunchMode.inAppWebView
: Uses an in-app web view to launch the URL.LaunchMode.externalApplication
: Handles the URL by an external application.LaunchMode.externalNonBrowserApplication
: Handles the URL by a non-browser application.
You can use this parameter to control how the URL is launched, for example:
await launchUrl(uri, mode: LaunchMode.inAppWebView);
In conclusion, opening a web browser (URL) from your Flutter code is easy with the url_launcher
package. You can add this package to your project and use it like shown in the example above. If you need to launch URLs with special characters or control how they are launched, you will need to take into account the changes in Flutter 3 and above.