I solved this by using the stream readers and writers instead of single read/write statements like this:
StreamSubscription<NDEFMessage> readFromTag() {
try {
// ignore: cancel_subscriptions
StreamSubscription<NDEFMessage> subscription =
NFC.readNDEF().listen((tag) {
}, onDone: () {
_stream = null;
}, onError: (e) {
_stream = null;
if (!(e is NFCUserCanceledSessionException)) {
showDialog(
context: Get.context,
builder: (context) => AlertDialog(
title: const Text("Error!"),
content: Text(e.toString()),
),
);
}
});
return subscription;
} catch (err) {
print("error: $err");
_stream?.cancel();
_stream = null;
return _stream;
}
}
and then use this streams onData method to handle the the data on the tag like this:
StreamSubscription<NDEFMessage> _stream;
void _readNFC(BuildContext context) async {
if (_stream == null) {
_stream = nfc.readFromTag();
if (_stream != null) {
_stream.onData((data) async {
print("Data found in stream: ${data.payload}");
if (readData != null || readData.isNotEmpty) {
//handle data
} else {
print("Empty Tag!");
}
});
}
}
}
and then don't forget to dispose the streams in dispose function.