Reputation: 420
I am developing a mobile app with Flutter.
I am just wondering how to send an SMS message from the app.
NewCustomIconButton(
text: 'SMS',
icon: Icons.sms,
onPressed: () async {
await Clipboard.setData(ClipboardData(
text:
"Hello, ${confirmedBooking.userAccountID}, you have booking with ${_artistAccount.getFullname()}, "));
UrlLauncher.launch(
"sms://${confirmedBooking.phoneNumber}");
},
),
)
In this code, if I press the button, it goes SMS screen on my phone, however, I am just wondering if it is possible that sending an SMS message without manually typing the text.
Thanks for reading,
I am waiting for your help.
Upvotes: 2
Views: 2100
Reputation: 4854
If you'd like to send an SMS
directly from the code, you could use the sms package:
NB: the sms
package supports only Android as for now
import 'package:sms/sms.dart';
SmsSender sender = new SmsSender();
String address = someAddress();
SmsMessage message = new SmsMessage(address, 'Hello from Flutter!');
message.onStateChanged.listen((state) {
if (state == SmsMessageState.Sent) {
print("SMS is sent");
} else if (state == SmsMessageState.Delivered) {
print("SMS is delivered");
}
});
sender.sendSms(message);
If you'd like to open a new SMS
message prefilled with specified content and recipient, you could do so by launching the following URI
:
sms://${confirmedBooking.phoneNumber}?body=${messageBody}
Remember to encode the String
to get a valid URI
:
String uriAndroid = "sms:${confirmedBooking.phoneNumber}?body=${messageBody}";
String uriIOS = "sms:${confirmedBooking.phoneNumber}&body=${messageBody}";
uriAndroid = Uri.encodeFull(uriAndroid);
uriIOS = Uri.encodeFull(uriIOS); // valid URIs
For reference, follows a full code snippet according to your specific scenario:
NewCustomIconButton(
text: 'SMS',
icon: Icons.sms,
onPressed: () async {
String smsContent =
"Hello, ${confirmedBooking.userAccountID}, you have booking with ${_artistAccount.getFullname()}";
await Clipboard.setData(ClipboardData(
text: smsContent));
String char = Platform.isAndroid ? '?' : '&';
UrlLauncher.launch(
Uri.encodeFull("sms:${phoneNumber}${char}body=${smsContent}"));
},
),
)
I'd also suggest to create a reusable function:
void createNewSms(String phoneNumber, String smsContent) {
String char = Platform.isAndroid ? '?' : '&';
UrlLauncher.launch(
Uri.encodeFull("sms:${phoneNumber}${char}body=${smsContent}"));
}
Upvotes: 3