Flutter Stuff

How to Open SMS App with Number and Text in Flutter

How to Open SMS App with Number and Text in Flutter

Have you ever needed to open the SMS app on an Android device to send a text message from within your Flutter app? Maybe you’re building a chat app, a help center, or a customer support interface, and you want to make it easy for users to send a text message to your support team.

Whatever the reason, I’ve got you covered! In this blog post, I’ll show you how to open the SMS app with a specific number and text in Flutter. It’s easier than you think!

Step 1: Add the `url_launcher` Package

First, you’ll need to add the `url_launcher` package to your Flutter project. You can do this by running the following command in your terminal:

flutter pub add url_launcher
Dart


This package allows you to launch external apps, including the SMS app.

Step 2: Import the `url_launcher` Package

Next, import the `url_launcher` package in your Dart file:

import 'package:url_launcher/url_launcher.dart';
Dart

Step 3: Define the SMS Intent

To open the SMS app, you’ll need to define the intent that specifies the number and text. Here’s an example:

const smsNumber = '1234567890'; // Replace with the desired number
const smsText = 'Hello, this is a test message!';
final Uri smsIntentUri = Uri(
scheme: 'smsto',
path: '${smsNumber}',
queryParameters: {
'body': smsText,
},
);
Dart


In this example, we’re defining a URI that specifies the SMS intent. The `scheme` is set to `’smsto’`, which is the scheme used for SMS intents. The `path` is set to the desired phone number, and the `queryParameters` is set to the text message.

Step 4: Launch the SMS Intent

Finally, use the `launch` function from `url_launcher` to launch the SMS intent:

await launch(smsIntentUri.toString());
Dart

That’s it! When you run this code, it will open the SMS app with the specified number and text.

Example Code

Here’s the complete code example:

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(
    title: 'SMS App Opener',
    home: Scaffold(
    appBar: AppBar(
    title: Text('SMS App Opener'),
),
body: Center(
  child: ElevatedButton(
  child: Text('Open SMS App'),
  onPressed: () {
  const smsNumber = '1234567890'; // Replace with the desired number
  const smsText = 'Hello, this is a test message!';
  final Uri smsIntentUri = Uri(
    scheme: 'smsto',
    path: '${smsNumber}',
    queryParameters: {
    'body': smsText,
},
);
    await launch(smsIntentUri.toString());
        },
        ),
      ),
      ),
    );
  }
}
Dart

Leave a Comment

Scroll to Top