How to Launch URL in Flutter

URL launcher

URL launcher is a common thing nowadays in any sort of application. In this article, we will see about how to launch an website url. We are going to use an simple package from names url_launcher.

Adding the url_launcher plugin to the dependency

pubspec.yaml file adding dependency

Add the url_launcher plugin in the dependencies in pubspec.yaml file. Then click on the pub get on the top.

importing package

On the main.dart file, import the package for using it in our code.

Create an function for performing the url launcher exception handling

_launchURL() function

In this article, I am naming the function as “_launchURL()”. Since URLs are asynchronous, this function should wait for the url to request and respond back. In the function,
* We should create a constant for declaring the url(website url), in our case we are naming it as url.
Now, we should write a simple if-else condition for checking if the url exists or not and respond to us.
* canLaunch(url) is the keyword for sending the request to the website and respond us back to the app to proceed further.
* launch(url) is the keyword to launch the url in our app. If the url does not exist, it should throw an error, so we can throw it easily using throw keyword.
* Now then, that’s all we need to look into it for the function. Now we can easily incorporate it in our app

Note: asynchronous means the app need to request the website and then the website need to respond back to the app. While these process taking place, the app should wait for the respond from the website.

Create a StalessWidget

  • After creating the stateless widget, for simplicity just create a RaisedButton in the body of the scaffold which is inside the materialapp widget.
  • On the onpressed property, give our _launchURl function to execute.
  • That’s it, the url will be launched from our app.
urlLauncher app

Entire code:

You can also find the entire code for the project here:

Thank you for reading.