Enable Dark Mode!
how-to-install-and-configure-flutter-url-launcher.jpg
By: Nihala MK

How to Install & Configure Flutter url_launcher

Flutter

A Flutter package called URL launcher provides an easy-to-use method for calling, texting, sending, and launching URLs from within a Flutter application. With its array of features, we can easily launch an external program or service that is capable of handling a specific URL scheme.

How to Install & Configure Flutter url_launcher

First, use this command to install the url_launcher package.
$ flutter pub add url_launcher  
Add the following dependents to the dependencies section of your project's pubspec.yaml file:
dependencies: url_launcher: ^5.4.5
Then open your dart code and import the package:
import 'package:url_launcher/url_launcher.dart';

Project Structure   

Update AndroidManifest.xml 
<queries>
   <!-- If your app checks for SMS support -->
   <intent>
       <action android:name="android.intent.action.VIEW" />
       <data android:scheme="sms" />
   </intent>
   <!-- If your app checks for call support -->
   <intent>
       <action android:name="android.intent.action.VIEW" />
       <data android:scheme="tel" />
   </intent>
   <!-- If your application checks for inAppBrowserView launch mode support -->
   <intent>
       <action android:name="android.support.customtabs.action.CustomTabsService" />
   </intent>
</queries>
Main.dart
The provided Flutter code showcases a simple application that demonstrates the use of the url_launcher package to interact with external applications and services. This application allows users to either make phone calls or open URLs in a web browser directly from the app. Here's a simplified explanation of how the app works:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:url_launcher/link.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
 runApp(const MyApp());
}
class MyApp extends StatelessWidget {
 const MyApp({super.key});
 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'URL Launcher',
     theme: ThemeData(
       primarySwatch: Colors.blue,
     ),
     home: const MyHomePage(title: 'URL Launcher'),
   );
 }
}
class MyHomePage extends StatefulWidget {
 const MyHomePage({super.key, required this.title});
 final String title;
 @override
 State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
 bool _hasCallSupport = false;
 Future<void>? _launched;
 String _phone = '';
 @override
 void initState() {
   super.initState();
   // Check for phone call support.
   canLaunchUrl(Uri(scheme: 'tel', )).then((bool result) {
     setState(() {
       _hasCallSupport = result;
     });
   });
 }
 Future<void> _launchInBrowser(Uri url) async {
   if (!await launchUrl(
     url,
     mode: LaunchMode.externalApplication,
   )) {
     throw Exception('Could not launch $url');
   }
 }
 Future<void> _launchInWebView(Uri url) async {
   if (!await launchUrl(url, mode: LaunchMode.inAppWebView)) {
     throw Exception('Could not launch $url');
   }
 }

 Widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) {
   if (snapshot.hasError) {
     return Text('Error: ${snapshot.error}');
   } else {
     return const Text('');
   }
 }
 Future<void> _makePhoneCall(String phoneNumber) async {
   final Uri launchUri = Uri(
     scheme: 'tel',
     path: phoneNumber,
   );
   await launchUrl(launchUri);
 }
 @override
 Widget build(BuildContext context) {
   // onPressed calls using this URL are not gated on a 'canLaunch' check
   // because the assumption is that every device can launch a web URL.
   final Uri toLaunch =
   Uri(scheme: 'https', host: 'www.cybrosys.com',);
   return Scaffold(
     appBar: AppBar(
       title: Text(widget.title),
     ),
     body: ListView(
       children: <Widget>[
         Column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: <Widget>[
             Padding(
               padding: const EdgeInsets.all(16.0),
               child: TextField(
                   onChanged: (String text) => _phone = text,
                   decoration: const InputDecoration(
                       hintText: 'Input the phone number to launch')),
             ),
             ElevatedButton(
               onPressed: _hasCallSupport
                   ? () => setState(() {
                 _launched = _makePhoneCall(_phone);
               })
                   : null,
               child: _hasCallSupport
                   ? const Text('Make phone call')
                   : const Text('Calling not supported'),
             ),
             Padding(
               padding: const EdgeInsets.all(16.0),
               child: Text(toLaunch.toString()),
             ),
             ElevatedButton(
               onPressed: () => setState(() {
                 _launched = _launchInBrowser(toLaunch);
               }),
               child: const Text('Launch in browser'),
             ),
             const Padding(padding: EdgeInsets.all(16.0)),
             const Padding(padding: EdgeInsets.all(16.0)),
             const Padding(padding: EdgeInsets.all(16.0)),
             const Padding(padding: EdgeInsets.all(16.0)),
             Link(
               uri: Uri.parse(
                   'https://www.cybrosys.com'),
               target: LinkTarget.blank,
               builder: (BuildContext ctx, FollowLink? openLink) {
                 return TextButton.icon(
                   onPressed: openLink,
                   label: const Text('Link Widget documentation'),
                   icon: const Icon(Icons.read_more),
                 );
               },
             ),
             const Padding(padding: EdgeInsets.all(16.0)),
             FutureBuilder<void>(future: _launched, builder: _launchStatus),
           ],
         ),
       ],
     ),
   );
 }
}
Structure
* Main Entry: The app kicks off with the main() function that runs the MyApp widget.
* MyApp Widget: This is a stateless widget that returns a MaterialApp with a title and a theme. It sets the MyHomePage as the home screen.
* MyHomePage Widget: A stateful widget that creates a dynamic interface allowing users to input a phone number and interact with buttons to launch URLs or make phone calls.
Functionality
* Initialization: When MyHomePage is initialized, it checks if the device can make phone calls and updates its state accordingly.
* Making Phone Calls: If the device supports it, users can input a phone number. Upon pressing a button, the app attempts to make a phone call to the entered number.
* Launching URLs: The app includes functionality to open a specific URL (in this case, "https://www.cybrosys.com") in the device's external web browser. There's also an example of using a Link widget for navigating to URLs directly within the app interface.
* User Interface: The UI comprises a text field for entering the phone number, buttons to initiate actions (making a call or launching a URL), and a Link widget for inline linking. Feedback on the operation's success or failure is displayed through the UI.
* Asynchronous Operations: Checking device capabilities, making phone calls, and launching URLs are handled asynchronously, ensuring that the app remains responsive.
Conclusion
This Flutter app is a practical demonstration of how developers can integrate external linking and communication capabilities into their applications, enhancing interactivity and providing users with valuable functionalities. Through the url_launcher package, Flutter apps can easily interact with other apps and services on the device, making them more versatile and user-friendly.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 


whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message