nfc_manager 1.3.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 89

nfc_manager #

A Flutter plugin to manage the NFC features. Supported on both Android and iOS.

Setup #

Android Setup #

iOS Setup #

Usage #

Managing Session #

// Check availability
bool isAvailable = await NfcManager.instance.isAvailable();

// Start session and register callback.
NfcManager.instance.startTagSession(onDiscovered: (NfcTag tag) async {
  // Manipulating tag
});

// Stop session and unregister callback.
NfcManager.instance.stopSession();

Manipulating NDEF #

// Obtain an Ndef instance from tag
Ndef ndef = Ndef.fromTag(tag);

if (ndef == null) {
  print('Tag is not ndef');
  return;
}

// Get an NdefMessage instance cached at discovery time
NdefMessage cachedMessage = ndef.cachedMessage;

// Create an NdefMessage instance you want to write.
NdefMessage message = NdefMessage([
  NdefRecord.createText('Hello'),
  NdefRecord.createUri(Uri.parse('https://flutter.dev')),
  NdefRecord.createMime('text/plain', Uint8List.fromList('Hello'.codeUnits)),
  NdefRecord.createExternal('mydomain', 'mytype', Uint8List.fromList('mydata'.codeUnits)),
]);

if (!ndef.isWritable) {
  print('Tag is not ndef writable');
  return;
}

// Write an NdefMessage
try {
  await ndef.write(message);
} catch (e) {
  // handle error
  return;
}

Manipulating Platform-Specific-Tag #

The following platform-specific-tag classes are available:

iOS

  • MiFare
  • FeliCa
  • ISO15693
  • ISO7816

Android

  • NfcA
  • NfcB
  • NfcF
  • NfcV
  • IsoDep

Example

MiFare miFare = MiFare.fromTag(tag);

if (miFare == null) {
  print('MiFare is not available on this tag');
  return;
}

Uint8List response = await miFare.sendMiFareCommand(...);

1.3.1 #

  • fix a bug where the error callback was not called.

1.3.0 #

  • add callback to handle error from session.

1.2.0 #

  • make discovered callback async.

1.1.0+1 #

  • update readme.

1.1.0 #

  • add constants.
  • fix misspelled name.
  • fix xcode build warning.
  • increase the Flutter SDK requirement to ^1.10.0.

1.0.1 #

  • fix error on invoking transceive method.

1.0.0 #

  • add platform-specifc-tag operations.
  • remove NfcSessionType enum.
  • migrate to pubspec platforms manifest.
  • more consistent naming.

0.5.1 #

  • update flutter project files.
  • additional fix for migration to AndroidX.

0.5.0 #

  • migrate to AndroidX.

0.4.0+2 #

  • fix typo on README

0.4.0+1 #

  • update README

0.4.0 #

  • rename NfcNdef#cachedNdef to NfcNdef#cachedMessage.
  • add NfcSessionType enum.
  • add NfcTagPollingOption enum.

0.3.0 #

  • add NdefRecord#createMimeRecord.
  • add optional parameters alertMessageIOS and errorMessageIOS displayed in iOS system UI.
  • fix error on deserializing null message on dart side.

0.2.0 #

  • split startSession into startNdefSession and startTagSession.
  • improve doc.

0.1.1 #

  • fix crash on serializing nil message on ios side.
  • add example project.
  • improve doc.

0.1.0+2 #

  • improve doc.

0.1.0+1 #

  • improve doc.

0.1.0 #

  • add iOS 13 features.

0.0.1 #

  • initial release.

example/lib/main.dart

import 'dart:typed_data';

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  ValueNotifier<dynamic> result = ValueNotifier(null);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('NfcManager Plugin Example')),
        body: SafeArea(
          child: FutureBuilder<bool>(
            future: NfcManager.instance.isAvailable(),
            builder: (context, ss) => ss.data != true
              ? Center(child: Text('NfcManager.isAvailable(): ${ss.data}'))
              : Flex(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                direction: Axis.vertical,
                children: [
                  Flexible(
                    flex: 2,
                    child: Container(
                      margin: EdgeInsets.all(4),
                      constraints: BoxConstraints.expand(),
                      decoration: BoxDecoration(border: Border.all()),
                      child: SingleChildScrollView(
                        child: ValueListenableBuilder<dynamic>(
                          valueListenable: result,
                          builder: (context, value, _) => Text('${value ?? ''}'),
                        ),
                      ),
                    ),
                  ),
                  Flexible(
                    flex: 3,
                    child: GridView.count(
                      padding: EdgeInsets.all(4),
                      crossAxisCount: 2,
                      childAspectRatio: 4,
                      crossAxisSpacing: 4,
                      mainAxisSpacing: 4,
                      children: [
                        RaisedButton(child: Text('Tag Read'), onPressed: _tagRead),
                        RaisedButton(child: Text('Ndef Write'), onPressed: _ndefWrite),
                        RaisedButton(child: Text('Ndef Write Lock'), onPressed: _ndefWriteLock),
                      ],
                    ),
                  ),
                ],
              ),
          ),
        ),
      ),
    );
  }

  void _tagRead() {
    NfcManager.instance.startTagSession(onDiscovered: (NfcTag tag) async {
      result.value = tag.data;
      NfcManager.instance.stopSession();
    });
  }

  void _ndefWrite() {
    NfcManager.instance.startTagSession(onDiscovered: (NfcTag tag) async {
      Ndef ndef = Ndef.fromTag(tag);
      if (ndef == null) {
        result.value = 'Tag is not ndef';
        NfcManager.instance.stopSession(errorMessageIOS: result.value);
        return;
      }

      NdefMessage message = NdefMessage([
        NdefRecord.createText('Hello World!'),
        NdefRecord.createUri(Uri.parse('https://flutter.dev')),
        NdefRecord.createMime('text/plain', Uint8List.fromList('Hello'.codeUnits)),
        NdefRecord.createExternal('com.example', 'mytype', Uint8List.fromList('mydata'.codeUnits)),
      ]);

      try {
        await ndef.write(message);
        result.value = 'Success to "Ndef Write"';
        NfcManager.instance.stopSession();
      } catch (e) {
        result.value = e;
        NfcManager.instance.stopSession(errorMessageIOS: result.value.toString());
        return;
      }
    });
  }

  void _ndefWriteLock() {
    NfcManager.instance.startTagSession(onDiscovered: (NfcTag tag) async {
      Ndef ndef = Ndef.fromTag(tag);
      if (ndef == null) {
        result.value = 'Tag is not ndef';
        NfcManager.instance.stopSession(errorMessageIOS: result.value.toString());
        return;
      }

      try {
        await ndef.writeLock();
        result.value = 'Success to "Ndef Write Lock"';
        NfcManager.instance.stopSession();
      } catch (e) {
        result.value = e;
        NfcManager.instance.stopSession(errorMessageIOS: result.value.toString());
        return;
      }
    });
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  nfc_manager: ^1.3.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:nfc_manager/nfc_manager.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
77
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
89
Learn more about scoring.

We analyzed this package on Mar 31, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health suggestions

Format lib/src/nfc_manager/nfc_manager.dart.

Run flutter format to format lib/src/nfc_manager/nfc_manager.dart.

Format lib/src/nfc_manager/nfc_ndef.dart.

Run flutter format to format lib/src/nfc_manager/nfc_ndef.dart.

Format lib/src/translator.dart.

Run flutter format to format lib/src/translator.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test