You will learn how you can send a particular message to your friend on Whatsapp app on both IOS and Android using your own Flutter application.
1. Use url_launcher package as library
Open this file : pubspec.yaml
Under dependencies add this:
dependencies:
url_launcher: ^5.4.1
Note : Take care of indentation in this file, it is very important otherwise it won't work.
2. Install the package by ‘Packages get’
If you are using terminal then add the command pub get
On Android studio you can see the pub get option on top of pubspec.yaml file.
3. Import the package in your dart file where you are implementing this functionality
import ‘package:url_launcher/url_launcher.dart’;
Also import ‘dart:io’ to find out the exact platform of the app, eg. IOS or Android.
import 'dart:io';
4. Create the function for launching the app
void launchWhatsApp({
@required String phone,
@required String message,
}) async {
String url() {
if (Platform.isIOS) {
return "whatsapp://wa.me/$phone/?text=${Uri.parse(message)}";
} else {
return "whatsapp://send?phone=$phone&text=${Uri.parse(message)}";
}
}
if (await canLaunch(url())) {
await launch(url());
} else {
throw 'Could not launch ${url()}';
}
}
This function takes two parameters first the phone number and second your message.
5. For IOS only : Add this code to info.plist under Runner folder in ios folder
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
6. Call the function whenever required
When you want to launch whatsapp contact with a pre filled message, just call the above function providing the phone number and your message.
=> The format of passing the phone number is very important.
For example,
=> if your number in international format is +001-(XXX)XXXXXXX, then write it as 1XXXXXXXXXX
=> if your number in international format is +91-(XXX)XXXXXXX, then write it as 91XXXXXXXXXX
Well done, now you can now launch Whatsapp form your flutter app with phone number and custom message.
If you have any doubts please
mention in the comments section.
Thank you for your patience
reading. If you enjoyed this post, I’d be very grateful if you’d help it
spread by emailing it to a friend, or sharing it on Whatsapp or Facebook.
😇Happy Learning!!