how to get mobile messages using flutter

Issue

I have to get messages from mobile so I am using this plugin. It is working but I get no messages, just printing the result Instance of 'SmsMessage' in the console, but I did everything specified in document example. did I make any mistakes?

source code

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:sms/sms.dart';

class MessagesScreen extends StatefulWidget {
  MessagesScreen({Key key}) : super(key: key);

  @override
  _MessagesScreenState createState() => _MessagesScreenState();
}

class _MessagesScreenState extends State<MessagesScreen> {
  List _allMessages;
  @override
  void initState() {
    super.initState();

    getAllMessages();
  }

  Future getAllMessages() async {
    SmsQuery query = new SmsQuery();
    List<SmsMessage> messages = await query.getAllSms;
    debugPrint("Total Messages : " + messages.length.toString());
    print(messages);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Messages"),
      ),
      body: ListView.builder(
        itemCount: 1,
        itemBuilder: (BuildContext context, int index) {
          return Text("Test");
        },
      ),
    );
  }
}

console screenshot

Solution

The behavior you describe is actually normal. The messages will be returned as an instance of the SmsMessage class.

When you try to print an object, it is converted to a string. By default the toString method will display Instance of "Class name"; and in your case, that’s why you are having that output, you are trying to print a list of objects.

If for each of the messages, you would like to display the body, this code snippet should help you:

Future getAllMessages() async {
    SmsQuery query = new SmsQuery();
    List<SmsMessage> messages = await query.getAllSms;
    debugPrint("Total Messages : " + messages.length.toString());
    messages.forEach((element) { print(element.body); });
}

Answered By – Steve

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

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