这是一个简单的代码块,用于检测来自 SMS 的交易:
FlutterLocalNotificationsPlugin notificationsPlugin =
FlutterLocalNotificationsPlugin();
onBackgroundMessage(SmsMessage message) async {
log("Message recieved in background");
_TransactionState().onMessage(message);
}
class Transaction extends StatefulWidget {
const Transaction({Key? key}) : super(key: key);
@override
State<Transaction> createState() => _TransactionState();
}
class _TransactionState extends State<Transaction> {
String _message = "";
var debit = 0.0;
var credit = 0.0;
var last = 0.0;
var transact = 0.0;
final Telephony telephony = Telephony.instance;
@override
void initState() {
super.initState();
initPlatformState();
}
onMessage(SmsMessage message) async {
setState(() {
bool mesFlag = false;
bool debFlag = false;
if (message.body!.contains('debit')) {
debFlag = true;
} //check whether debit or credit
for (var bank in banks.entries) {
if (message.address!.contains(bank.key)) {
_message = message.body?.split(
' ')[(debFlag ? bank.value.item2 : bank.value.item1)] ??
"Error reading transaction!";
_message = _message.replaceAll(',', ''); //remove comma
if (_message.contains("Rs.")) {
_message = _message.substring(3);
} else if (_message.contains("Rs")) {
_message = _message.substring(2);
} // remove Rs. and Rs
showNotification("Last transaction amount: $_message");
transact = double.parse(_message);
mesFlag = true;
if (debFlag) {
debit += transact;
last = -transact;
} else {
credit += transact;
last = transact;
}
limit += last;
if (limit < 0) {
limit = 0;
showNotification("You are over-spending!");
}
transList.add(TransactionTile(trans: last));
break;
}
}
if (!mesFlag) _message = ''; //if not a transaction
});
}
这是我在后台收到短信时抛出的异常:
setState() called in constructor: _TransactionState#f0921(lifecycle state: created, no widget, not mounted)
This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.
电话包要求 onBackgroundMessage
成为一个全局函数。是否有任何解决方法,我可以通过它在全局函数中调用 onMessage
或 setState()
因为即使应用程序未打开我也需要更新它们并且它的功能应该与 onMessage
功能完全一样。
感谢任何帮助。