搜尋套件、儲存庫與 APP 分類

套件詳情v2.0.5

nfc_in_flutter

適用於 Android 和 iOS 的 Flutter 插件,用於讀取和寫入 NFC 標籤。目前僅支援讀取 NDEF 格式標籤。

近 30 天下載
124
喜歡數
107
Pub 分數
40

安裝套件

flutter pub add nfc_in_flutter

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

nfc_in_flutter 是一個 Flutter 插件,可在 Android 和 iOS 上實現 NFC 標籤讀取功能,目前僅支援 NDEF 格式的標籤。它提供了一個簡單的介面,用於偵測和取得 NFC 標籤中的資料,非常適合需要非接觸式資料交換的應用程式。此套件專為希望以最少設定實作跨平台 NFC 功能的開發者設計。雖然支援唯讀功能,但寫入作業尚未支援。該套件持續維護且為開源項目,文件與範例皆可於 GitHub 倉儲取得。

適用情境

  • 在零售應用中讀取NDEF標籤
  • 啟用非接觸式存取控制
  • 促進活動簽到
  • 透過NFC傳輸小資料
  • 與智慧海報整合

主要特色

  • 跨平台支援(Android 與 iOS)
  • 僅讀取NDEF標籤
  • NFC檢測的簡單API
  • 開源且持續維護
  • 輕量級整合

適合對象

  • 需要NFC資料檢索的移動應用
  • 開發無接觸解決方案的開發者
  • 使用NDEF格式標籤的專案
  • 原型設計NFC功能
  • 面向 Android 和 iOS 使用者的應用

使用建議

  • 寫操作不支援
  • 僅限NDEF格式
  • 需要設備相容性
  • iOS 可能限制了後台掃描
  • 平台特定的權限需要

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

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.

所屬分類

原始碼儲存庫

使用此套件的專案

暫無相關資料。