Sharing this Custom Action for those who might struggle to add an NFC reader in their App.
It is quite straightforward so you should have no issues with it, but if necessary, let me know if I can help with it.
On this example, I created an App State (String scannedNFCTag) to output the value of the NFC's scanned tag ID, in order to verify if it works properly.
Please note that you might have to compile and run the App in your mobile device in order to properly test the NFC functionalities.
Dependency: flutter_nfc_kit: ^3.4.2
Import: import 'package:flutter_nfc_kit/flutter_nfc_kit.dart';
Code for the Custom Action:
Future<void> thisShallScan() async {
var appState = FFAppState();
NFCAvailability availability;
try {
availability = await FlutterNfcKit.nfcAvailability;
} on PlatformException {
availability = NFCAvailability.not_supported;
}
if (availability == NFCAvailability.not_supported) {
print('NFC is not supported on this device.');
return;
}
try {
// Poll for the NFC tag
NFCTag tag = await FlutterNfcKit.poll();
updateNfcTagInAppState(appState, tag);
} catch (e) {
print('Error scanning NFC tag: $e');
}
}
void updateNfcTagInAppState(FFAppState appState, NFCTag? tag) {
if (tag == null) {
print('No NFC tag scanned.');
return;
}
// Get the ID of the scanned NFC tag
var currentTagId = tag.id;
// Update the app state with the scanned NFC tag ID
appState.update(() {
appState.scannedNFCTag = currentTagId;
});
}
You may use this in many ways, such as adapting to communicate with your Collections in a Widget:
Future<void> fetchUserName() async {
try {
if (tag != null) {
var snapshot = await FirebaseFirestore.instance
.collection('users')
.where("uNFC", isEqualTo: tag!.id)
.get();
if (snapshot.docs.isNotEmpty) {
var userData = snapshot.docs.first.data();
setState(() {
_userName = userData['display_name'];
});
} else {
setState(() {
_userName = 'User not found';
});
}
}
} catch (e) {
print('Error fetching user data: $e');
}
}
I hope this helps some of you.