In Flutter, url_launcher
is a package that allows you to launch URLs and email addresses, as well as make phone calls and send SMS messages. With this package, you can quickly and easily direct users to external resources like websites and social media platforms, and even open up email and phone applications directly from your app.
Installing the url_launcher package
To use the url_launcher
package, you need to add it to your project’s dependencies. To do this, simply add the following line to your project’s pubspec.yaml
file:
dependencies:
url_launcher: ^6.0.0
Then, run flutter pub get
to install the package and import it into your Dart file like so:
import 'package:url_launcher/url_launcher.dart';
Launching URLs
Once you have the url_launcher
package installed and imported, you can use it to launch URLs in the user’s default browser. Here’s an example of how to launch a URL:
String url = "https://www.google.com/";
if (await canLaunch(url)) {
await launch(url);
} else {
throw "Could not launch $url";
}
In this example, the canLaunch()
method checks if the device can launch the specified URL, and the launch()
method launches the URL in the user’s default browser. If the URL cannot be launched, the code throws an exception.
Making Phone Calls
To make a phone call using the url_launcher
package, you can use the tel
scheme in the URL. Here’s an example:
String phoneNumber = "+15555555555";
if (await canLaunch("tel:$phoneNumber")) {
await launch("tel:$phoneNumber");
} else {
throw "Could not launch phone call";
}
In this example, the tel:
scheme is used to indicate that a phone call should be made. The phone number is appended to the end of the URL.
Sending SMS Messages
You can also use the url_launcher
package to send SMS messages. Here’s an example:
String phoneNumber = "+15555555555";
if (await canLaunch("sms:$phoneNumber")) {
await launch("sms:$phoneNumber");
} else {
throw "Could not send SMS message";
}
In this example, the sms:
scheme is used to indicate that an SMS message should be sent. The phone number is appended to the end of the URL.
Launching Email
To launch an email app, you can use the mailto
scheme in the URL. Here’s an example:
String email = "example@example.com";
if (await canLaunch("mailto:$email")) {
await launch("mailto:$email");
} else {
throw "Could not launch email";
}
In this example, the mailto:
scheme is used to indicate that an email should be launched. The email address is appended to the end of the URL.
Conclusion
In conclusion, the url_launcher
package is a useful tool for opening external resources from within your Flutter app. With just a few lines of code, you can direct users to websites, make phone calls, send SMS messages, and even launch email applications. By integrating this package into your app, you can provide a seamless user experience and make it easier for users to access external resources.