nfc_flutter 0.0.1 copy "nfc_flutter: ^0.0.1" to clipboard
nfc_flutter: ^0.0.1 copied to clipboard

A Flutter plugin for NFC (Near Field Communication) on iOS and Android.

nfc_flutter #

A Flutter plugin for NFC (Near Field Communication) on iOS and Android.

Features #

  • Check NFC availability on the device
  • Get current NFC status (enabled/disabled/not available)
  • Discover NFC tags
  • Read NDEF records from tags
  • Write NDEF records to tags
  • Format tags to NDEF format
  • Check if a tag is NDEF compatible

Supported Platforms #

  • iOS: 13.0+ (requires CoreNFC framework)
  • Android: API level 21+ (requires NFC permissions)

Installation #

Add nfc_flutter to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  nfc_flutter: ^0.0.1

Then run flutter pub get to install the package.

Configuration #

iOS Configuration #

  1. Open your iOS project in Xcode
  2. Add the following to your Info.plist file:
<key>NFCReaderUsageDescription</key>
<string>Allow this app to use NFC</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
    <string>nfc</string>
</array>
  1. Enable NFC capability in your Xcode project:
    • Go to your project settings
    • Select the "Signing & Capabilities" tab
    • Click the "+" button to add a new capability
    • Select "Near Field Communication Tag Reading"
    • Make sure "CoreNFC" is added to your framework list

Android Configuration #

  1. Add the following permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.NFC" />
<uses-feature
    android:name="android.hardware.nfc"
    android:required="false" />
  1. Ensure your app has the necessary intent filters for NFC tag discovery:
<activity
    android:name=".MainActivity"
    android:exported="true"
    android:launchMode="singleTop">
    <!-- Add these intent filters for NFC tag discovery -->
    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.nfc.action.TAG_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

API Reference #

NfcFlutter #

The main class for NFC operations.

Methods

  • isAvailable(): Check if NFC is available on the device.

    • Returns: Future<bool>
  • getStatus(): Get the current NFC status.

    • Returns: Future<NfcStatus> (one of: enabled, disabled, notAvailable, unknown)
  • startTagDiscovery(): Start listening for NFC tags.

    • Returns: Stream<NfcTag>
  • stopTagDiscovery(): Stop listening for NFC tags.

    • Returns: Future<void>
  • readNdefRecords(NfcTag tag): Read NDEF records from a tag.

    • Parameters: tag - The NFC tag to read from
    • Returns: Future<List<NdefRecord>>
  • writeNdefRecords(NfcTag tag, List<NdefRecord> records): Write NDEF records to a tag.

    • Parameters:
      • tag - The NFC tag to write to
      • records - The NDEF records to write
    • Returns: Future<bool> (true if successful)
  • formatNdef(NfcTag tag): Format a tag to NDEF format.

    • Parameters: tag - The NFC tag to format
    • Returns: Future<bool> (true if successful)
  • isNdefCompatible(NfcTag tag): Check if a tag is NDEF compatible.

    • Parameters: tag - The NFC tag to check
    • Returns: Future<bool>

NfcTag #

Represents an NFC tag.

Properties

  • id: The unique identifier of the tag.
  • type: The type of the tag (e.g., iso14443, iso15693, mifare, etc.).
  • platformData: Platform-specific tag data.

NdefRecord #

Represents an NDEF (NFC Data Exchange Format) record.

Constructors

  • NdefRecord.uri(Uri uri): Create a URI record.
  • NdefRecord.text(String text, {String languageCode = 'en'}): Create a text record.

Usage Example #

import 'package:flutter/material.dart';
import 'package:nfc_flutter/nfc_flutter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'NFC Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'NFC Flutter Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _nfcFlutter = NfcFlutter();
  StreamSubscription<NfcTag>? _tagSubscription;
  String _message = 'Tap a NFC tag to read';

  @override
  void initState() {
    super.initState();
    _checkNfcAvailability();
  }

  Future<void> _checkNfcAvailability() async {
    final isAvailable = await _nfcFlutter.isAvailable();
    if (!isAvailable) {
      setState(() {
        _message = 'NFC is not available on this device';
      });
    }
  }

  void _startTagDiscovery() {
    setState(() {
      _message = 'Waiting for NFC tag...';
    });

    _tagSubscription = _nfcFlutter.startTagDiscovery().listen((tag) {
      setState(() {
        _message = 'Tag found: ${tag.id} (${tag.type})';
      });
      
      // Read NDEF records from the tag
      _nfcFlutter.readNdefRecords(tag).then((records) {
        if (records.isNotEmpty) {
          setState(() {
            _message += '\nRecords: ${records.length}';
          });
        }
      });
    });
  }

  void _stopTagDiscovery() {
    _tagSubscription?.cancel();
    _nfcFlutter.stopTagDiscovery();
    setState(() {
      _message = 'Tag discovery stopped';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _message,
              textAlign: TextAlign.center,
              style: Theme.of(context).textTheme.headline6,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _startTagDiscovery,
              child: const Text('Start Tag Discovery'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: _stopTagDiscovery,
              child: const Text('Stop Tag Discovery'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _tagSubscription?.cancel();
    _nfcFlutter.stopTagDiscovery();
    super.dispose();
  }
}

Notes #

  • iOS Limitations: iOS only supports reading NFC tags while the app is in the foreground and the user has granted permission.
  • Android Limitations: Android requires the app to have the necessary permissions and intent filters for NFC tag discovery.
  • NDEF Format: This plugin primarily supports NDEF (NFC Data Exchange Format) tags. Some tags may not be compatible with NDEF.
  • Foreground Dispatch: On Android, NFC tag discovery works best when the app is in the foreground using foreground dispatch.

License #

MIT License

Contributing #

Contributions are welcome! Please feel free to submit a Pull Request.

Issues #

If you encounter any issues, please file an issue on the GitHub repository.

1
likes
150
points
137
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin for NFC (Near Field Communication) on iOS and Android.

Homepage

Documentation

API reference

License

MIT (license)

Dependencies

flutter

More

Packages that depend on nfc_flutter

Packages that implement nfc_flutter