Debug School

rakesh kumar
rakesh kumar

Posted on

How to integrate whatsapp msg in flutter

Without specific package
Method: Using url_launcher Package
With Specific Package
WhatsApp Business API:
Register for a WhatsApp Business API account.
Use the WhatsApp Business API SDK for Flutter.
Third-party services:
Twilio: Offers WhatsApp messaging integration through their API.
Nexmo: Provides WhatsApp messaging integration through their API.
MessageBird: Offers WhatsApp messaging integration through their API.
Flutter packages:
whatsapp_fluter: A Flutter package for sending WhatsApp messages.
flutter_whatsapp: A Flutter package for sharing content on WhatsApp.
Keep in mind that these packages might have limitations and requirements, such as:

  • WhatsApp Business API approval
  • Phone number verification
  • Message templates
  • Content restrictions

Method: Using url_launcher Package

If you want to send WhatsApp messages from a Flutter app, there are a few different ways to achieve this without relying on specific packages like whatsapp_flutter or flutter_whatsapp. You can use URL schemes, which are supported by both iOS and Android, to open WhatsApp directly with a pre-filled message. Here's how you can do it using the url_launcher package.

Method: Using url_launcher Package
The url_launcher package allows you to interact with other apps (such as opening WhatsApp) from your Flutter app by launching URLs. This is a lightweight and effective way to integrate WhatsApp functionality.

Step 1: Add url_launcher Dependency
Add the following to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^6.1.7
Enter fullscreen mode Exit fullscreen mode

Make sure to run flutter pub get to fetch the package.

Step 2: Import the Package

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
Enter fullscreen mode Exit fullscreen mode

Step 3: Implement the Code
Here’s the complete example of how to send a WhatsApp message using the url_launcher package:

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: WhatsAppDemo(),
    );
  }
}

class WhatsAppDemo extends StatefulWidget {
  @override
  _WhatsAppDemoState createState() => _WhatsAppDemoState();
}

class _WhatsAppDemoState extends State<WhatsAppDemo> {
  final TextEditingController _phoneNumberController = TextEditingController();
  final TextEditingController _messageController = TextEditingController();

  // Function to open WhatsApp with a pre-filled message
  void openWhatsApp() async {
    String phone = _phoneNumberController.text;
    String message = _messageController.text;

    if (phone.isNotEmpty && message.isNotEmpty) {
      String whatsappUrl = "https://wa.me/$phone?text=${Uri.encodeFull(message)}";

      // Check if the device can launch the URL
      if (await canLaunch(whatsappUrl)) {
        await launch(whatsappUrl);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("WhatsApp is not installed or cannot open the URL.")),
        );
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Please enter both a phone number and a message.")),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WhatsApp Message Sender'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: _phoneNumberController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                labelText: 'Enter Phone Number (e.g., +1234567890)',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            TextField(
              controller: _messageController,
              decoration: InputDecoration(
                labelText: 'Enter Message',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: openWhatsApp,
              child: Text('Send Message via WhatsApp'),
            ),
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

How This Works
url_launcher is used to open the WhatsApp URL scheme https://wa.me/.
The openWhatsApp() method constructs the URL using the entered phone number and message.
canLaunch() checks if the device can open the URL, and launch() executes it.
Notes
Ensure that the phone number is in the international format, including the country code (e.g., +1234567890).
This method works on both iOS and Android devices as long as WhatsApp is installed.
This method is straightforward and doesn’t require a dedicated WhatsApp package, making it a clean and efficient solution for integrating WhatsApp messaging into your Flutter app.

Using flutter_open_whatsapp Package

The flutter_open_whatsapp package allows you to open WhatsApp and send a message to a specific number or simply open a chat. Here’s how you can integrate and use it.

Step 1: Add Dependency
Add the flutter_open_whatsapp package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_open_whatsapp: ^2.0.2
Enter fullscreen mode Exit fullscreen mode

Make sure to run flutter pub get after adding the dependency.

Step 2: Import the Package

import 'package:flutter/material.dart';
import 'package:flutter_open_whatsapp/flutter_open_whatsapp.dart';
Step 3: Implement the Code
Here's the complete code example to send a WhatsApp message using flutter_open_whatsapp:

dart
Copy code
import 'package:flutter/material.dart';
import 'package:flutter_open_whatsapp/flutter_open_whatsapp.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: WhatsAppDemo(),
    );
  }
}

class WhatsAppDemo extends StatefulWidget {
  @override
  _WhatsAppDemoState createState() => _WhatsAppDemoState();
}

class _WhatsAppDemoState extends State<WhatsAppDemo> {
  final TextEditingController _phoneNumberController = TextEditingController();
  final TextEditingController _messageController = TextEditingController();

  // Function to send message via WhatsApp
  void sendMessage() {
    String phone = _phoneNumberController.text;
    String message = _messageController.text;

    if (phone.isNotEmpty && message.isNotEmpty) {
      FlutterOpenWhatsapp.sendSingleMessage(phone, message);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Please enter both a phone number and a message.")),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WhatsApp Message Sender'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: _phoneNumberController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                labelText: 'Enter Phone Number (e.g., +1234567890)',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            TextField(
              controller: _messageController,
              decoration: InputDecoration(
                labelText: 'Enter Message',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: sendMessage,
              child: Text('Send Message via WhatsApp'),
            ),
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

How This Works
The FlutterOpenWhatsapp.sendSingleMessage(phone, message); method is used to open WhatsApp with the given phone number and pre-filled message.
The _phoneNumberController and _messageController are used to capture the user's input for the phone number and message, respectively.
Additional Notes
The phone number should include the country code (e.g., +1234567890).
Ensure that WhatsApp is installed on the device; otherwise, the package won't work.
This package directly integrates with WhatsApp to send messages, making it quick and easy to implement without manually constructing URLs.
This example demonstrates how to send a WhatsApp message in Flutter using the flutter_open_whatsapp package, providing a clean and effective way to implement WhatsApp messaging functionality in your app.

Top comments (0)