How do I open a web browser (URL) from my Flutter code?
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>
Then the following should word - for flutter 3 upwards:
const uri = Uri.parse("https://flutter.io");
if (await canLaunchUrl(uri)){
await launchUrl(uri);
} else {
// can't launch url
}
or for older versions of flutter use this instead:
const url = "https://flutter.io";
if (await canLaunch(url)){
await launch(url);
} else {
// can't launch url
}
launchUrl
has a mode
parameter which can be used to control where the url gets launched.
So, passing in launchUrl(uri, mode: LaunchMode.platformDefault)
leaves the decision of how to launch the URL to the platform
implementation. But you can also specify
LaunchMode.inAppWebView
which will use an in-app web view
LaunchMode.externalApplication
for it to be handled by an external application
Or LaunchMode.externalNonBrowserApplication
to be handled by a non-browser application.
TL;DR
This is now implemented as Plugin
const url = "https://flutter.io";
if (await canLaunchUrl(url))
await launchUrl(url);
else
// can't launch url, there is some error
throw "Could not launch $url";
Full example:
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 { const url = 'https://flutter.io'; if (await canLaunch(url)) { await launch(url); } else { throw 'Could not launch $url'; } }
In pubspec.yaml
dependencies:
url_launcher: ^5.7.10
Special Characters:
If the url
value contains spaces or other values that are now allowed in URLs, use
Uri.encodeFull(urlString)
or Uri.encodeComponent(urlString)
and pass the resulting value instead.