Read Inbox Messages - Flutter SMS Retriever

In this post we are going to learn how to read all Messages from inbox in Flutter.

For this we are going to use sms plugin.

Let's start

Step 1: Create flutter application

Step 2: Add dependencies

add sms dependencies in pubspec.yaml file and run flutter pub get on terminal

dev_dependencies:
  flutter_test:
    sdk: flutter
  sms: ^0.2.4

 

Step 3: Create dart file and add below code

class MyInbox extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return MyInboxState();
  }

}

class MyInboxState extends State{
  SmsQuery query = new SmsQuery();
  List messages=new List();
  @override
 initState()  {
    // TODO: implement initState
    super.initState();

  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("SMS Inbox"),
        backgroundColor: Colors.pink,
      ),
      body: FutureBuilder(
        future: fetchSMS() ,
        builder: (context, snapshot)  {

        return ListView.separated(
            separatorBuilder: (context, index) => Divider(
              color: Colors.black,
            ),
            itemCount: messages.length,
            itemBuilder: (context,index){
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: ListTile(
              leading: Icon(Icons.markunread,color: Colors.pink,),
              title: Text(messages[index].address),
              subtitle: Text(messages[index].body,maxLines:2,style: TextStyle(),),
            ),
          );
        });
      },)
    );
  }

  fetchSMS()
  async {
    messages = await query.getAllSms;
  }
}

add  import 'package:sms/sms.dart';

To handle the SMS we need to create instance of SmsQuery

SmsQuery query = new SmsQuery();

in the above we are using the Future builder to read sms from Inbox by query.getAllSms method

This will return list of all messages from inbox.

Step 4: Update main dart file

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyInbox(),
    );
  }
}

 

Step 5: Run application

 

Add SMS Permissions in Manifest file