nfc_in_flutter
nfc in flutter is a plugin for reading and writing nfc tags in flutter. it works on both android and ios with a simple stream interface.
usage
read nfc tags
// nfc.readndef returns a stream of ndefmessage
stream<ndefmessage> stream = nfc.readndef();
stream.listen((ndefmessage message) {
print("records: ${message.records.length}");
});
read one nfc tag
ndefmessage message = await nfc.readndef(once: true).first;
print("payload: ${message.payload}");
// once: true` only scans one tag!
writing to tags
you can access a message’s nfc tag using the ndefmessage
‘s .tag
property. the tag has a .write
method, which allows you to write a ndef message to the tag.
note that the read stream must still be open when the .write
method is called. this means that the once
argument in .readndef()
cannot be used.
stream<ndefmessage> stream = nfc.readndef();
stream.listen((ndefmessage message) {
ndefmessage newmessage = ndefmessage.withrecords(
ndefrecord.mime("text/plain", "hello world")
);
message.tag.write(newmessage);
});
you can also use the nfc.writendef(ndefmessage)
method, which wraps the code above with support for the once
argument.
ndefmessage newmessage = ndefmessage.withrecords(
ndefrecord.mime("text/plain", "hello world")
);
stream<ndeftag> stream = nfc.writendef(newmessage);
stream.listen((ndeftag tag) {
print("wrote to tag");
});
if you only want to write to one tag, you can set the once
argument to true.
ndefmessage newmessage = ndefmessage.withrecords(
ndefrecord.mime("text/plain", "hello world")
);
stream<ndeftag> stream = nfc.writendef(newmessage, once: true);
stream.listen((ndeftag tag) {
print("only wrote to one tag!");
});
and if you would rather use a future
based api, you can await the returned stream’s .first
method.
ndefmessage newmessage = ndefmessage.withrecords(
ndefrecord.type("text/plain", "hello world")
);
await nfc.writendef(newmessage, once: true).first;
example
import 'package:nfc_in_flutter/nfc_in_flutter.dart';
class nfcreader extends statefulwidget {
@override
_nfcreaderstate createstate() => _nfcreaderstate();
}
class _nfcreaderstate extends state {
bool _supportsnfc = false;
bool _reading = false;
streamsubscription<ndefmessage> _stream;
@override
void initstate() {
super.initstate();
// check if the device supports nfc reading
nfc.isndefsupported
.then((bool issupported) {
setstate(() {
_supportsnfc = issupported;
});
});
}
@override
widget build(buildcontext context) {
if (!_supportsnfc) {
return raisedbutton(
child: const text("you device does not support nfc"),
onpressed: null,
);
}
return raisedbutton(
child: text(_reading ? "stop reading" : "start reading"),
onpressed: () {
if (_reading) {
_stream?.cancel();
setstate(() {
_reading = false;
});
} else {
setstate(() {
_reading = true;
// start reading using nfc.readndef()
_stream = nfc.readndef(
once: true,
throwonusercancel: false,
).listen((ndefmessage message) {
print("read ndef message: ${message.payload}"),
}, onerror: (e) {
// check error handling guide below
});
});
}
}
);
}
}
full example in example directory
installation
add nfc_in_flutter
to your pubspec.yaml
dependencies:
nfc_in_flutter: ^2.0.3
ios
on ios you must add turn on the near field communication capability, add a nfc usage description and a nfc entitlement.
turn on near field communication tag reading
open your ios project in xcode, find your project’s target and navigate to capabilities. scroll down to ‘near field communication tag reading’ and turn it on.
turning on ‘near field communication tag reading’
- adds the nfc tag-reading feature to the app id.
- adds the near field communication tag reader session formats entitlement to the entitlements file.
from developer.apple.com: building an nfc tag-reader app
nfc usage description
open your ios/runner/info.plist
file and add a new nfcreaderusagedescription
key. it’s value should be a description of what you plan on using nfc for.
<key>nfcreaderusagedescription</key>
<string>...</string>
android
add the following to your app’s androidmanifest.xml
file:
<uses-permission android:name="android.permission.nfc" />
if your app requires nfc, you can add the following to only allow it to be downloaded on devices that supports nfc:
<uses-feature android:name="android.hardware.nfc" android:required="true" />
“what is ndef?”
if you’re new to nfc you may come to expect a lot of readnfc()
calls, but instead you see readndef()
and ndefmessage
. ndef is just a formatting standard the tags can be encoded in. there are other encodings than ndef, but ndef is the most common one. currently nfc in flutter only supports ndef formatted tags.
host card emulation
nfc in flutter supports reading from emulated host cards*.
to read from emulated host cards, you need to do a few things.
- call
readndef()
with thereadermode
argument set to an instance ofnfcdispatchreadermode
. - insert the following
<intent-filter />
in yourandroidmanifest.xml
activity:
<intent-filter>
<action android:name="android.nfc.action.ndef_discovered" />
<category android:name="android.intent.category.default" />
</intent-filter>
- not properly tested on ios
⚠️ multiple reader modes
if you start a readndef()
stream with the reader mode set to an instance of nfcdispatchreadermode
, while another stream is active with the nfcnormalreadermode
, it will throw a nfcmultiplereadermodesexception
.
platform differences
when you call readndef()
on ios, core nfc (the ios framework that allows nfc reading) opens a little window. on android it just starts listening for nfc tag reads in the background.
image from developer.apple.com: near field communication
⚠️ this will also freeze flutter while open. please send a pull request if you can fix this.
error handling
errors are no exception to nfc in flutter (hah, get it). the stream returned by nfc.readndef()
can send 7 different exceptions, and even worse: they are different for each platform!
see the full example in the example directory for an example on how to check for errors.
exceptions for both platforms
ndefreadingunsupportedexception
thrown when a reading session is started, but not actually supported.
ios
nfcusercanceledsessionexception
thrown when the user clicks cancel/done core nfc popup. if you don’t need to know if the user canceled the session you can start reading with the throwonusercancel
argument set to false
like so: readndef(throwonusercancel: false)
nfcsessiontimeoutexception
core nfc limits nfc reading sessions to 60 seconds. nfcsessiontimeoutexception
is thrown when the session has been active for 60 seconds.
nfcsessionterminatedunexpectedlyexception
thrown when the reading session terminates unexpectedly.
nfcsystemisbusyexception
throw when the reading session fails because the system is too busy.
android
nfcioexception
thrown when a i/o exception occurs. will for example happen if a tag is lost while being read or a tag could not be connected to.
ndefbadformatexception
thrown when the tag is expected to ndef formatted, but it is incorrectly formatted.
Comments are closed.