Tuesday, January 26, 2021

Url Launcher || Flutter

Url Launcher || Flutter 

The Url Launcher is used to launch other services
Phonebook
SMS
Email
Apps
Browser
WebView

dependencies
https://pub.dev/packages/url_launcher/install
  url_launcher: ^5.7.10

Note - 
was url launchar does not work on android 11 by If you donot add this line in manifest.xml
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

or
<manifest>

    <!-- Nest within the manifest element, not the application element-->
    <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="https" />
        </intent>
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="*/*" />
        </intent>
    </queries>

    <application>
        ....
    </application>
</manifest>
........................................................................................................................................................................................................................
Example :#1
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(MyApp());
  }
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Home(),
      );
    }
  }
    class Home extends StatefulWidget {
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
      child: RaisedButton(
        onPressed: _launchURL,
        child: Text('Show Flutter homepage'),
      ),
    ),
          
        );
      }
    }

_launchURL() async {
  const url = 'https://flutter.dev';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

Happy Coding :)
........................................................................................................................................................................................................................
Example :#2

Utils.dart
import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';

class Utils {
  static Future openLink({
    @required String url,
  }) =>
      _launchUrl(url);

  static Future openEmail({
    @required String toEmail,
    @required String subject,
    @required String body,
  }) async {
    final url =
        'mailto:$toEmail?subject=${Uri.encodeFull(subject)}&body=${Uri.encodeFull(body)}';

    await _launchUrl(url);
  }

  static Future openPhoneCall({@required String phoneNumber}) async {
    final url = 'tel:$phoneNumber';

    await _launchUrl(url);
  }

  static Future openSMS({@required String phoneNumber}) async {
    final url = 'sms:$phoneNumber';

    await _launchUrl(url);
  }

  static Future _launchUrl(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    }
  }
}
..................................
main.dart
import 'package:flutter/material.dart';
import 'package:urllaunchers/utils.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final String title = 'Url Launcher';

  @override
  Widget build(BuildContext context) => MaterialApp(
        title: title,
        theme: ThemeData(primarySwatch: Colors.deepOrange),
        home: MainPage(title: title),
      );
}

class MainPage extends StatefulWidget {
  final String title;

  const MainPage({
    @required this.title,
  });

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              buildButton(
                text: 'Open Link',
                onClicked: () => Utils.openLink(url: 'http://flutter.dev'),
              ),
              buildButton(
                text: 'Open Email',
                onClicked: () => Utils.openEmail(
                  toEmail: 'example@gmail.com',
                  subject: 'Hello World',
                  body: 'This works great!',
                ),
              ),
              buildButton(
                text: 'Open Call',
                onClicked: () =>
                    Utils.openPhoneCall(phoneNumber: '+4912388128311'),
              ),
              buildButton(
                text: 'Open SMS',
                onClicked: () => Utils.openSMS(phoneNumber: '+4912388128311'),
              ),
            ],
          ),
        ),
      );

  Widget buildButton({
    @required String text,
    @required VoidCallback onClicked,
  }) =>
      Container(
        padding: EdgeInsets.symmetric(vertical: 12),
        child: RaisedButton(
          shape: StadiumBorder(),
          onPressed: onClicked,
          color: Colors.red,
          textColor: Colors.white,
          child: Text(
            text,
            style: TextStyle(fontSize: 24),
          ),
        ),
      );
}
Happy Coding :)
........................................................................................................................................................................................................................
Example :#3
//Add the url_laucher package in your pubspec.yaml

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Url Launcher',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: UrlLauncher(),
    );
  }
}

class UrlLauncher extends StatefulWidget {
  @override
  _UrlLauncherState createState() => _UrlLauncherState();
}

Future<void> _launched;

//To open phonebook
Future<void> _callUsers(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

//To open Messaging app
Future<void> _smsUsers(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

//To open email/gmail
Future<void> _mailUsers(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

//To open installed app in the device
Future<void> _launchUniversalLinkIos(String url) async {
  if (await canLaunch(url)) {
    final bool nativeAppLaunchSucceeded = await launch(
      url,
      forceSafariVC: false,
      universalLinksOnly: true,
    );
    if (!nativeAppLaunchSucceeded) {
      await launch(
        url,
        forceSafariVC: true,
      );
    }
  }
}

//To open link in browser
Future<void> _launchInBrowser(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

//To open link in webView
Future<void> _launchInWebView(String url) async {
  if (await canLaunch(url)) {
    await launch(
      url,
      forceSafariVC: true,
      forceWebView: true,
      headers: <String, String>{'my_header_key': 'my_header_value'},
    );
  } else {
    throw 'Could not launch $url';
  }
}

class _UrlLauncherState extends State<UrlLauncher> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 2,
        children: <Widget>[
          LauncherButton(
            color: Color(0xffF3D180),
            icon: Icons.phone,
            text: 'Phone',
            onPress: () => setState(() {
              _launched = _callUsers('tel:95521515');
            }),
          ),
          LauncherButton(
            color: Color(0xffFCBF49),
            icon: Icons.sms,
            text: 'SMS',
            onPress: () => setState(() {
              _launched = _smsUsers('sms:5550101234');
            }),
          ),
          LauncherButton(
            color: Color(0xffF77F00),
            icon: Icons.mail,
            text: 'Email',
            onPress: () => setState(() {
              _launched = _mailUsers(
                  'mailto:smith@example.org?subject=UrlPackage&body=It%20is%20awesome');
            }),
          ),
          LauncherButton(
            color: Color(0xffD62828),
            icon: Icons.play_arrow,
            text: 'Youtube',
            onPress: () => setState(() {
              _launched = _launchUniversalLinkIos('https://www.youtube.com/');
            }),
          ),
          LauncherButton(
            color: Color(0xff2E933C),
            icon: Icons.public,
            text: 'Brower',
            onPress: () => setState(() {
              _launched = _launchInBrowser('https://www.google.com/');
            }),
          ),
          LauncherButton(
            color: Color(0xff1B4965),
            icon: Icons.http,
            text: 'WebView',
            onPress: () => setState(() {
              _launched = _launchInWebView('https://www.google.com/');
            }),
          ),
        ],
      ),
    );
  }
}

class LauncherButton extends StatelessWidget {
  final Color color;
  final IconData icon;
  final Function onPress;
  final String text;

  const LauncherButton({this.color, this.icon, this.onPress, this.text});
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress,
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Container(
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(
              25.0,
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(
                icon,
                size: 60,
                color: Colors.white,
              ),
              Text(
                text,
                style: TextStyle(
                  height: 2,
                  fontSize: 20,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Happy Coding:)
........................................................................................................................................................................................................................
Example :#4

No comments:

Post a Comment