URLs in Flutter

14 Jun, 2022
While surfing the net, every user will come across many buttons, text, etc., that would redirect the user to a different webpage in the same tab or in a different tab when clicked. In the same way, when a developer links a URL to a button or text in an app, the app will open the website when clicked in the following ways:
 In browser(default) In-App
 In browser(default)
 In-App
When it comes to opening a website in a browser then it involves two apps at work. One of the app that the user is using and the other is the browser. But, when it comes to, in-app opening, it involves only one app. Each of these features can be used by a developer according to the need of the user.
In Flutter, everything is a widget and in the same way, Flutter also uses a lot of plugins or dependencies in order to make the app work faster and easier. In this case, the “url_launcher” plugin can be used to launch the URL in a mobile application.
Step 1: Open “pubspec.yaml” file from the project folder.
pubspec.yaml
Step 2: In the pubspec.yaml file, type “url_launcher:” under dependencies.
The code looks like this:
Dart
dependencies:  flutter:    sdk: flutter  url_launcher:
Step 3: Now click “Pub Get” button in the top of the application (Android Studio).
Step 4: The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully.
Step 5: Now import the plugin or package by adding the “import ‘package:url_launcher/url_launcher.dart’;” code to the top of the “main.dart” file.
Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a URL, to open it in a browser. 
Dart
_launchURLBrowser() async {  var url = Uri.parse("https://www.geeksforgeeks.org/");  if (await canLaunchUrl(url)) {    await launchUrl(url);  } else {    throw 'Could not launch $url';  }}
This is what we did in the above function:
The function is named here as “_launchURLBrowser” and the function is declared as “async”, so that it returns a promise.
The “url” variable is assigned with the required web address, as a string. It is declared as a “const”, so that the variable is not changed at any circumstance.
 If there is a possibility to launch the URL, only then the url is launched by calling the launch() function with url variable as an attribute.
 Else, it will throw/print a text with the URLs value, as an error message.
Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a URL, to open it in the app.
Dart
_launchURLApp() async {  var url = Uri.parse("https://www.geeksforgeeks.org/");  if (await canLaunchUrl(url)) {    await launchUrl(url);  } else {    throw 'Could not launch $url';  }}
This is what we did in the above function:
The function is named here as “_launchURLApp” and the function is declared as “async”, so that it returns a promise.
The “url” variable is assigned with the required web address, as a string. It is declared as a “const”, so that the variable is not changed at any circumstance.
If there is a possibility to launch the URL, only then the url is launched by calling the launch() function with url variable as an attribute.
In order to open the URL inside the app, two conditions have to be made true.
 forceWebView: true — this helps the app to start the web view of the app for the website to open inside the app itself.forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser.
 forceWebView: true — this helps the app to start the web view of the app for the website to open inside the app itself.
forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser.
5) Else, it will throw/print a text with the url value, as an error message.
Note: In browser opening, the forceWebView and forceSafariVC are set to “false” by default.
The above functions can be called whenever needed in code, by calling the name of the functions as such. The examples are as follows:
Dart
ElevatedButton(                 onPressed: _launchURLBrowser,                 style: ButtonStyle(                   padding:                       MaterialStateProperty.all(const EdgeInsets.all(5.0)),                   textStyle: MaterialStateProperty.all(                     const TextStyle(color: Colors.black),                   ),                 ),   ElevatedButton(                 onPressed: _launchURLApp,                 style: ButtonStyle(                   padding:                       MaterialStateProperty.all(const EdgeInsets.all(5.0)),                   textStyle: MaterialStateProperty.all(                     const TextStyle(color: Colors.black),                   ),                 ),
In the above code block we did two things:
This creates two raised buttons having the text “Open in Browser” and “Open in App” on it, respectively. For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp respectively so that, when the first button is pressed the URL is opened in a browser and when the second button is pressed the URL is opened in the app itself.
This creates two raised buttons having the text “Open in Browser” and “Open in App” on it, respectively.
 For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp respectively so that, when the first button is pressed the URL is opened in a browser and when the second button is pressed the URL is opened in the app itself.
Dart
// importing dependenciesimport 'package:flutter/material.dart';import 'package:url_launcher/url_launcher.dart'; // function to trigger the build processvoid main() => runApp(const MyApp()); _launchURLBrowser() async {  var url = Uri.parse("https://www.geeksforgeeks.org/");  if (await canLaunchUrl(url)) {    await launchUrl(url);  } else {    throw 'Could not launch $url';  }} _launchURLApp() async {  var url = Uri.parse("https://www.geeksforgeeks.org/");  if (await canLaunchUrl(url)) {    await launchUrl(url);  } else {    throw 'Could not launch $url';  }} class MyApp extends StatelessWidget {  const MyApp({Key? key}) : super(key: key);   @override  Widget build(BuildContext context) {    return MaterialApp(      home: Scaffold(        appBar: AppBar(          title: const Text('Geeks for Geeks'),          backgroundColor: Colors.green,        ),        body: SafeArea(          child: Center(            child: Column(              children: [                Container(                  height: 250.0,                ),                const Text(                  'Welcome to GFG!',                  style: TextStyle(                    fontSize: 30.0,                    color: Colors.green,                    fontWeight: FontWeight.bold,                  ),                ),                Container(                  height: 20.0,                ),                ElevatedButton(                  onPressed: _launchURLBrowser,                  style: ButtonStyle(                    padding:                        MaterialStateProperty.all(const EdgeInsets.all(5.0)),                    textStyle: MaterialStateProperty.all(                      const TextStyle(color: Colors.black),                    ),                  ),                  // textColor: Colors.black,                  // padding: const EdgeInsets.all(5.0),                  child: const Text('Open in Browser'),                ),                Container(                  height: 20.0,                ),                ElevatedButton(                  onPressed: _launchURLApp,                  style: ButtonStyle(                      padding:                          MaterialStateProperty.all(const EdgeInsets.all(5)),                      textStyle: MaterialStateProperty.all(                          const TextStyle(color: Colors.black))),                  // textColor: Colors.black,                  // padding: const EdgeInsets.all(5.0),                  child: const Text('Open in App'),                ),              ],            ),          ),        ),      ),    );  }}
ankit_kumar_
android
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.