skip to Main Content

I have been trying to write a simple flutter code and trying to send SMS using telephony. Sending Sms via the default SMS app works (telephony.sendSmsByDefaultApp()) but not sending directly from the app.

My code is as follows:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              sendSMS();
            },
            child: Text("Send SMS"),
          ),
        ),
      ),
    );
  }

  void sendSMS() async {
    final Telephony telephony = Telephony.instance;
    bool? permissionsGranted = await telephony.requestPhoneAndSmsPermissions;
    print(permissionsGranted);

    await telephony.sendSms(to: "+92xxxxxxxxxx", message: "Hello, this is a test message.");
    print("SMS Sent");
  }
}

I have added the following required permissions

<uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

2

Answers


  1. can you try the code

    https://d7networks.com/docs/Messages/Send_Message/

    we need to have an account on https://d7networks.com/ platform.

    Login or Signup to reply.
  2. Have you tried changing that onPressed() function in the ElevatedButton(), to an async function:

    ElevatedButton(
        onPressed: () async {
          await sendSMS();
        },
        child: Text("Send SMS"),
      )
    

    And then change your sendSMS() function to return a Future<void>, instead of void:

    Future<void> sendSMS() async {
        final Telephony telephony = Telephony.instance;
        bool? permissionsGranted = await telephony.requestPhoneAndSmsPermissions;
        print(permissionsGranted);
    
        await telephony.sendSms(to: "+92xxxxxxxxxx", message: "Hello, this is a test message.");
        print("SMS Sent");
      }
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search