Cross-platform flutter plugin for reading and writing NFC tags. Not maintained anymore - not looking for new maintainer, fork instead.

Overview

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.

⚠️ Currently only NDEF formatted tags are supported.

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.5

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

'Turn on Near Field Communication Tag Reading' capability  turned on for a project in Xcode

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 the readerMode argument set to an instance of NFCDispatchReaderMode.
  • Insert the following <intent-filter /> in your AndroidManifest.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
  • (Improvement) text read/write on iOS/Android is working, but want image or file

    (Improvement) text read/write on iOS/Android is working, but want image or file

    Any way to read/write image/pdf file on NFC tag using this packages ? Even, is this possible for NFC to read/write 1/2/3 MB file ?

    How we can achieve this ?

    opened by jams032 0
  •   NFC.isNDEFSupported not working

    NFC.isNDEFSupported not working

    NFC.isNDEFSupported
        .then((bool isSupported) {
      setState(() {
    
        _supportsNFC = isSupported;
    
      });
    });
    

    _supportNFC is returning false everytime

    opened by sudhanshujuyal 0
  • Remove usage of jCenter

    Remove usage of jCenter

    🐛 Bug Report This library still uses jCenter. jCenter doesn't get any updates anymore and should therefor be switched to mavenCentral.

    See also https://developer.android.com/studio/build/jcenter-migration

    Expected behavior No dependencies on jCenter

    Platform: 🤖 Android

    opened by ayadlaaouissi 0
  • getting Serial Number of NFC Card

    getting Serial Number of NFC Card

    Hi there ,

    I want to get Serial Number of NFC Card by using nfc_in_flutter

    I can get id, TNF, type, payload, data, and language. But unfortunately I can not get Serial number of NFC Card.

    Is there any solution, please?

    opened by akramytech 1
  • Migration to the V2 embedding

    Migration to the V2 embedding

    Hello! I've upgraded my app to flutter 2.5+. And upon pub get command I have received the following output:

    The plugins `nfc_in_flutter` use a deprecated version of the Android embedding.
    To avoid unexpected runtime failures, or future build failures, try to see if these plugins support the Android V2 embedding. Otherwise, consider removing them since a future release of Flutter will remove these deprecated APIs.
    If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
    

    Can you please upgrade the plugin to the latest V2 embedding? Thanks!

    opened by andriy-gulak-ew 1
Releases(v2.0.5)
  • v2.0.5(Jul 18, 2020)

    • Better reading reliability on iOS
    • New property rawPayload on NDEFRecord which contains the full, unedited record payload (#54 by @laurensfischer).
    Source code(tar.gz)
    Source code(zip)
  • v2.0.4(Mar 9, 2020)

    • CoreNFC is now a weak_framework. This should fix a crash on iOS devices that doesn't support NFC. (#28 by @mxpazyj)
    • Added alertMessage argument to readNDEF(). This controls the message on the iOS NFC modal. (#25 by @dghilardi)
    • Actually fixed NDEFRecord.languageCode being ignored when writing (what v2.0.3 tried to, but failed)
    • Support for reading and writing to empty tags on Android (#24)
    • Fixed CoreNFC crashing after cancelling reading multiple times in a row (https://github.com/semlette/nfc_in_flutter/issues/29#issuecomment-572241500 by @martyfuhry)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.3(Dec 9, 2019)

  • v2.0.2(Dec 6, 2019)

  • v2.0.1(Oct 23, 2019)

  • v2.0.0(Oct 4, 2019)

    • Added noSounds flag to NFCNormalReaderMode

    On Android, this tells the system not to play sounds when a NFC chip is scanned.

    • Support for writing NDEF messages has been added

    Get acccess to tags using the new .tag property on messages, which you can use to connect and write to tags.

    • Added the following methods for constructing NDEF messages:

    NDEFRecord.empty for empty records

    NDEFRecord.plain for text/plain records

    NDEFRecord.type for records with custom types

    NDEFRecord.text for records with well known text types

    NDEFRecord.uri for records with well known URI types

    NDEFRecord.absoluteUri

    NDEFRecord.external

    NDEFRecord.custom

    • COULD BE BREAKING: Records with type T and U (with well known TNF) will now be correctly constructed. URI records will have the URL prefix added to the .payload and Text records will now correctly have thr first prefix byte removed from the .payload. If you want the precise value, you can use the new .data property which excludes the URL prefix of URI records and language codes of Text records.

    • Added .data property to NDEFRecord which excludes URL prefixes and language codes from records with well known types.

    • Added .languageCode property to NDEFRecord which will contain the language code of a record with a well known text type.

    • Updated the .tnf property on NDEFRecords. This is now an enumerable (NFCTypeNameFormat) with it's value mapped to the correct TNF value. This works on both Android and iOS where as it previously did not.

    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jul 18, 2019)

  • v1.1.1(Jul 11, 2019)

  • v1.1.0(Jul 6, 2019)

  • v1.0.0(Jun 23, 2019)

Owner
Andi Semler
The force is strong with this one
Andi Semler
An app for small and medium organizations (SME) manager, with NFC-tag, e-tag and QR code features supported.

BK LAB Manager - an app for group management 1. Getting Started An app for small and medium organizations (SME) manager, with NFC-tag, e-tag and QR co

Andrew Ng 4 Sep 20, 2022
null 1 Jan 8, 2022
Permission plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check permissions.

Flutter permission_handler plugin The Flutter permission_handler plugin is build following the federated plugin architecture. A detailed explanation o

Baseflow 1.6k Sep 29, 2022
Dumbo - A collection of all dumb stuff at one place, this repo is to be maintained for people who just simply are taking break from huge stuff and practicing something.

dumbo A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is

Krish Bhanushali 1 Jan 3, 2022
A collection of useful packages maintained by the Flutter team

Flutter Packages This repo is a companion repo to the main flutter repo. It contains the source code for Flutter's first-party packages (i.e., package

Flutter 2.1k Sep 26, 2022
Actively maintained, community-driven Firebase BaaS for chat applications with an optional chat UI.

Flutter Firebase Chat Core Actively maintained, community-driven Firebase BaaS for chat applications with an optional chat UI. Flyer Chat is a platfor

Flyer Chat 156 Sep 23, 2022
A fork/modification of flutter epub view package

epub_view Pure flutter widget for view EPUB documents on all platforms. Based on epub package. Render with flutter widgets (not native view) on any pl

Geeky Geeky 0 Dec 28, 2021
Fluttersettingsui - Fork of settingsui. Create native settings for Flutter app in a minutes.

Settings UI for Flutter Installing: In your pubspec.yaml dependencies: flutter_settings_ui: ^1.0.1 import 'package:flutter_settings_ui/flutter_setti

Julian Steenbakker 23 Jul 21, 2022
Rich text editor for Flutter based on Delta format (Quill fork)

Visual Editor Visual Editor is a Rich Text editor for Flutter originally forked from Flutter Quill. The editor is built around the powerful Delta docu

Visual Space 147 Sep 19, 2022
Flutter package to render html as widgets that supports hyperlink, image, audio, video, iframe and many other tags.

HtmlWidget monorepo This repo contains the source code for everything HtmlWidget-related. Name Link flutter_widget_from_html_core flutter_widget_from_

Đào Hoàng Sơn 409 Sep 27, 2022
Flutter Plugin for Requesting and Writing Reviews in Google Play and the App Store

Flutter Plugin for Requesting and Writing Reviews in Google Play and the App Store. Apps have to be published for the app to be found correctly.

Flutter Community 265 Sep 15, 2022
A Flutter widget for rendering static html as Flutter widgets (Will render over 80 different html tags!)

flutter_html A Flutter widget for rendering HTML and CSS as Flutter widgets. Screenshot 1 Screenshot 2 Screenshot 3 Table of Contents: Installing Curr

Matthew Whitaker 1.5k Sep 23, 2022
A simple tag editor for inputing tags in Flutter.

Super Tag Editor A simple tag editor for inputting tags with suggestion box Supported suggestion box Screen Shot 1 Screen Shot 2 ) Usage Add the packa

dab 4 Aug 20, 2022
Allows tags to be entered inside textfield

textfield_tags This is a widget that allows your users to create tags by entering the tag's name inside of textfield and make the tags appear in the t

Eyoel Defare 71 Sep 23, 2022
A Clean looking modren and colorful notes app using a local database with sqflite

A Clean looking modren and colorful notes app using a local database with sqflite

Moaz Talaat 2 Sep 4, 2022
A flutter package that developers have pretty logs instead just printing everything like a newbie

A flutter package that developers have pretty logs instead just printing everything like a newbie. Features Makes it easy to log to console without us

null 2 Nov 28, 2021
A Flutter widget to set time with spinner instead of material time picker

flutter_time_picker_spinner Time Picker widget with spinner instead of a material time picker. 12H format 24H format 24H format with second Custom sty

Bobby Stenly Irawan 34 Aug 8, 2022
A simple screen that is shown when your app gets crashed instead of the normal crash dialog. It's very similar to the one in Flutter.

Red Screen Of Death What A simple screen that is shown when your app gets crashed instead of the normal crash dialog. It's very similar to the one in

Ahmad Melegy 178 Sep 8, 2022