Flutter open whatsapp with number

To open WhatsApp with a specific number in Flutter, you can utilize the url_launcher package. First, make sure to add the ‘url_launcher’ package to your pubspec.yaml file:


dependencies:
flutter:
sdk: flutter
url_launcher: ^6.0.3

After adding the dependency, run the “flutter pub get” command to fetch it.

Now, you can use the launch method from the ‘url_launcher’ package to open WhatsApp with a given number. Here’s an example:


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

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

class MyApp extends StatelessWidget {
// Replace the phone number with the desired number
final phoneNumber = "1234567890";

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Open WhatsApp'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
openWhatsApp();
},
child: Text('Open WhatsApp'),
),
),
),
);
}

void openWhatsApp() async {
// Add the country code to the phone number
final url = "https://wa.me/$phoneNumber";
if (await canLaunch(url)) {
await launch(url);
} else {
throw "Could not launch WhatsApp";
}
}
}

In the above example, we have a simple Flutter application that contains a button to open WhatsApp. When the button is pressed, it calls the ‘openWhatsApp’ function, which constructs the WhatsApp URL by appending the phone number to the ‘https://wa.me/’ base URL. The ‘canLaunch’ method checks if the URL can be launched, and then the ‘launch’ method is used to open WhatsApp. If the URL cannot be launched, an exception is thrown.

Make sure to replace the ‘phoneNumber’ variable with the desired phone number you want to open WhatsApp with, and add the necessary country code.

Remember to import the ‘url_launcher’ package at the top of your file: import ‘package:url_launcher/url_launcher.dart’;

Leave a comment