Dial USSD Service from a Flutter App: A Step-by-Step Guide
Image by Tosia - hkhazo.biz.id

Dial USSD Service from a Flutter App: A Step-by-Step Guide

Posted on

Are you tired of wondering how to integrate USSD service functionality into your Flutter app? Look no further! In this comprehensive guide, we’ll take you through the process of dialing a USSD service from a Flutter app. Get ready to unlock the power of USSD and take your app to the next level!

What is USSD?

USSD (Unstructured Supplementary Service Data) is a communication protocol used by mobile network operators to offer various services to their subscribers. It allows users to access information, perform transactions, and even interact with other users using simple, menu-driven commands. USSD is widely used for services like mobile money, banking, and directory inquiries.

Why Integrate USSD into Your Flutter App?

Integrating USSD into your Flutter app can open up a world of possibilities. Here are just a few reasons why:

  • Enhanced user experience**: By providing USSD functionality within your app, you can offer users a seamless experience, eliminating the need for them to exit your app and dial USSD codes manually.
  • Increase engagement**: USSD integration can lead to higher user engagement, as users are more likely to complete transactions and access services within your app.
  • Competitive advantage**: By offering USSD integration, you can differentiate your app from competitors and establish a unique value proposition.

Prerequisites

Before we dive into the implementation, make sure you have the following:

  1. A Flutter project set up in an IDE of your choice (e.g., Android Studio, Visual Studio Code).
  2. Android SDK (version 23 or higher) and Flutter SDK (version 2.0 or higher) installed.
  3. A mobile device or emulator with a working SIM card and mobile data connection.
  4. The USSD code you want to integrate (e.g., *123# for a mobile money service).

Step 1: Add the necessary dependencies

In your `pubspec.yaml` file, add the following dependencies:

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^6.0.10

The `url_launcher` package is used to launch the USSD dialer from within your app.

Step 2: Create a USSD dialer function

Create a new Dart file (e.g., `ussd_dialer.dart`) and add the following code:

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

Future dialUSSD(String ussdCode) async {
  final Uri uri = Uri.parse('tel:*$ussdCode');
  if (await canLaunchUrl(uri)) {
    await launchUrl(uri);
  } else {
    throw 'Could not launch USSD dialer';
  }
}

This function takes a USSD code as a string, constructs a `tel` URI, and then uses the `url_launcher` package to launch the USSD dialer.

Step 3: Call the USSD dialer function from your app

Create a button or any other UI element that will trigger the USSD dialer function. For example:

ElevatedButton(
  onPressed: () {
    dialUSSD('123#');
  },
  child: Text('Dial USSD'),
)

When the button is pressed, the `dialUSSD` function will be called with the specified USSD code.

Step 4: Handle USSD response (optional)

In some cases, you might want to handle the USSD response within your app. To do this, you’ll need to use a platform channel to communicate with the native USSD service.

Create a new file (e.g., `ussd_response_handler.dart`) and add the following code:

import 'package:flutter/services.dart';

class USSDResponseHandler {
  static const platform =
      const MethodChannel('com.example.ussd_response_handler');

  Future handleUSSDResponse(String ussdCode) async {
    final String response = await platform.invokeMethod('handleUSSDResponse', ussdCode);
    // Handle the response here
  }
}

This code defines a platform channel to communicate with the native USSD service. You’ll need to implement the native side of the platform channel in both Android and iOS platforms.

Native Implementation (Android)

In your Android module, create a new file (e.g., `USSDResponseHandler.java`) and add the following code:

package com.example.ussd_response_handler;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

public class USSDResponseHandler implements FlutterPlugin, MethodCallHandler {
  private Context context;
  private MethodChannel channel;

  @Override
  public void onAttachedToEngine(FlutterPluginBinding flutterPluginBinding) {
    context = flutterPluginBinding.getApplicationContext();
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "com.example.ussd_response_handler");
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(MethodCall call, Result result) {
    if (call.method.equals("handleUSSDResponse")) {
      String ussdCode = call.argument("ussdCode");
      // Handle the USSD response here
      result.success("USSD response handled successfully");
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
}

This code defines a platform channel to handle USSD responses on the Android platform.

Native Implementation (iOS)

In your iOS module, create a new file (e.g., `USSDResponseHandler.swift`) and add the following code:

import Flutter

public class USSDResponseHandler: NSObject, FlutterPlugin {
  private let channel: FlutterMethodChannel

  initCHANNEL(_ channel: FlutterMethodChannel) {
    self.channel = channel
  }

  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "com.example.ussd_response_handler", binaryMessenger: registrar.messenger())
    let instance = USSDResponseHandler(channel: channel)
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    if call.method == "handleUSSDResponse" {
      let ussdCode = call.arguments as? String
      // Handle the USSD response here
      result("USSD response handled successfully")
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

This code defines a platform channel to handle USSD responses on the iOS platform.

Conclusion

That’s it! You’ve successfully integrated USSD service functionality into your Flutter app. By following these steps, you can now provide your users with a seamless USSD experience, increasing engagement and setting your app apart from competitors. Remember to test your implementation thoroughly to ensure it works across different devices and platforms.

Platform USSD Code Response Handling
Android *123# Implemented using a platform channel
iOS *456# Implemented using a platform channel

Remember to replace the USSD codes with the actual codes you want to integrate into your app.

Frequently Asked Questions

  1. Q: Can I use this implementation for multiple USSD codes?

    A: Yes, you can modify the implementation to handle multiple USSD codes by adding multiple `dialUSSD` functions or using a single function with a USSD code as a parameter.

  2. Q: How do I handle USSD responses in my app?

    A: You can use a platform channel to handle USSD responses, as shown in the example. This allows you to communicate with the native USSD service and handle responses within your app.

  3. Q: What are the limitations of this implementation?

    A: This implementation assumes a basic understanding of Flutter and mobile app development. Additionally, USSD integration may not be

    Frequently Asked Questions

    Get your doubts cleared about dialing USSD service from a Flutter app!

    Can I dial a USSD code directly from my Flutter app?

    Yes, you can! Flutter provides a plugin called `url_launcher` that allows you to launch a USSD code from your app. You just need to format the USSD code as a tel URI and use the `launch()` function to open the dialer with the USSD code pre-filled.

    How do I format the USSD code as a tel URI?

    To format a USSD code as a tel URI, you need to prefix the USSD code with `tel:` and replace any asterisks (`*`) or number signs (`#`) with `*` and `%23` respectively. For example, if your USSD code is `*123#`, the tel URI would be `tel:*123%23`.

    Will the user be prompted to confirm before the USSD code is dialed?

    Yes, the user will be prompted to confirm before the USSD code is dialed. This is a security feature of Android and iOS to prevent apps from making unintended calls or dialing USSD codes without the user’s consent.

    Can I handle the response from the USSD service in my Flutter app?

    Unfortunately, it’s not possible to handle the response from the USSD service in your Flutter app, as the USSD service is handled by the device’s dialer app and not by your app. Once the USSD code is dialed, your app will not receive any response or feedback.

    Are there any platform-specific considerations I need to keep in mind?

    Yes, there are some platform-specific considerations to keep in mind. For example, on iOS, you need to add the `tel` scheme to your app’s `Info.plist` file, while on Android, you need to add the `android.permission.CALL_PHONE` permission to your app’s `AndroidManifest.xml` file.

Leave a Reply

Your email address will not be published. Required fields are marked *