I have a code like this:
SmsQuery query = new SmsQuery();
List<SmsMessage> AllMessages = [];
Timer? _timer;
var SMSPermStatus = Permission.sms.status;
@override
void initState() {
if (SMSPermStatus.isDenied == true) {
print("give me read SMS perm");
} else {
_timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
try {
GetAllMessages();
} catch(e) {
print("give me read SMS perm");
}
//GetAllMessages();
//Page();
print("refreshed");
print(AllMessages); // []
});
}
super.initState();
}
Future<void> GetAllMessages() async {
List<SmsMessage> messages = await query.querySms(
kinds: [SmsQueryKind.inbox],
count: 50,
);
setState(() {
AllMessages = messages;
});
}
If the application ha no permission to Read SMS, I want to print "no permission" to the console. But when I run the code I get this error:
How to solve the error? Thanks for help.
try
catch
will not work here because GetAllMessages
is a Future
.
Try await
-ing the Future
and adding async
to the callback
of Timer.periodic
.
Timer.periodic(Duration(seconds: 1), (t) async {
try {
await GetAllMessages();
} catch (e) {
print('exception caught: e');
}
});