Flutter NFC管理插件nfc_manager的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter NFC管理插件nfc_manager的使用

nfc_manager

nfc_manager 是一个用于在Flutter项目中访问Android和iOS设备NFC功能的插件。

注意: 此插件依赖于 NFCTagReaderSession(需要iOS 13.0或更高版本)和 NfcAdapter#enableReaderMode(需要Android API级别19或更高版本)。

Setup

Android Setup

iOS Setup

Usage

Handling Session

// 检查可用性
bool isAvailable = await NfcManager.instance.isAvailable();

// 启动会话
NfcManager.instance.startSession(
  onDiscovered: (NfcTag tag) async {
    // 使用NfcTag实例执行一些操作
  },
);

// 停止会话
NfcManager.instance.stopSession();

Handling Platform Tag

以下是可用的平台标签类:

  • Ndef
  • FeliCa(仅限iOS)
  • Iso7816(仅限iOS)
  • Iso15693(仅限iOS)
  • MiFare(仅限iOS)
  • NfcA(仅限Android)
  • NfcB(仅限Android)
  • NfcF(仅限Android)
  • NfcV(仅限Android)
  • IsoDep(仅限Android)
  • MifareClassic(仅限Android)
  • MifareUtralight(仅限Android)
  • NdefFormatable(仅限Android)

通过调用这些类上的工厂构造函数 from 来获取实例。例如:

Ndef? ndef = Ndef.from(tag);

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

// 使用Ndef实例执行一些操作

有关更多详细信息,请参阅 API文档

Real-World-App

请参考 此仓库,它演示了如何使用此插件。

示例代码

下面是一个完整的示例demo,展示了如何读取、写入和锁定NFC标签:

import 'dart:typed_data';

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  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: [
                            ElevatedButton(
                                child: Text('Tag Read'), onPressed: _tagRead),
                            ElevatedButton(
                                child: Text('Ndef Write'),
                                onPressed: _ndefWrite),
                            ElevatedButton(
                                child: Text('Ndef Write Lock'),
                                onPressed: _ndefWriteLock),
                          ],
                        ),
                      ),
                    ],
                  ),
          ),
        ),
      ),
    );
  }

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

  void _ndefWrite() {
    NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
      var ndef = Ndef.from(tag);
      if (ndef == null || !ndef.isWritable) {
        result.value = 'Tag is not ndef writable';
        NfcManager.instance.stopSession(errorMessage: 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(errorMessage: result.value.toString());
        return;
      }
    });
  }

  void _ndefWriteLock() {
    NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
      var ndef = Ndef.from(tag);
      if (ndef == null) {
        result.value = 'Tag is not ndef';
        NfcManager.instance.stopSession(errorMessage: 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(errorMessage: result.value.toString());
        return;
      }
    });
  }
}

这个示例应用程序包含了一个简单的UI,用户可以点击按钮来读取NFC标签、写入NDEF消息或将NFC标签锁定为只读。


更多关于Flutter NFC管理插件nfc_manager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter NFC管理插件nfc_manager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用nfc_manager插件进行NFC管理的代码示例。这个插件允许你读取和写入NFC标签。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加nfc_manager依赖:

dependencies:
  flutter:
    sdk: flutter
  nfc_manager: ^4.0.0  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 初始化NFC管理

在你的Flutter应用中,你需要先初始化NFC管理并检查设备是否支持NFC。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('NFC Manager Demo'),
        ),
        body: NfcManagerDemo(),
      ),
    );
  }
}

class NfcManagerDemo extends StatefulWidget {
  @override
  _NfcManagerDemoState createState() => _NfcManagerDemoState();
}

class _NfcManagerDemoState extends State<NfcManagerDemo> {
  bool _isNfcAvailable = false;

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

  Future<void> _checkNfcAvailability() async {
    bool isAvailable = await NfcManager.isNfcAvailable();
    if (mounted) {
      setState(() {
        _isNfcAvailable = isAvailable;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('NFC Available: $_isNfcAvailable'),
          if (_isNfcAvailable)
            ElevatedButton(
              onPressed: () => _startNfcSession(),
              child: Text('Start NFC Session'),
            )
          else
            Text('NFC is not available on this device.'),
        ],
      ),
    );
  }

  Future<void> _startNfcSession() async {
    // 这里你可以添加启动NFC会话的代码,比如开始监听NFC标签
  }
}

3. 读取NFC标签

_startNfcSession方法中,你可以开始监听NFC标签的读取事件:

Future<void> _startNfcSession() async {
  try {
    if (await NfcManager.startSession()) {
      NfcManager.addNdefListener(
        onDiscovered: (NfcNdefMessage message) async {
          // 处理读取到的NFC标签数据
          print('NFC Tag Discovered: $message');

          // 停止NFC会话
          await NfcManager.stopSession();
        },
      );
    } else {
      print('Failed to start NFC session.');
    }
  } catch (e) {
    print('Error: $e');
  }
}

4. 写入NFC标签(可选)

如果你想写入NFC标签,你可以使用NfcManager.writeNdefMessage方法。这里是一个简单的示例:

Future<void> _writeNfcTag(NfcNdefMessage message) async {
  try {
    bool success = await NfcManager.writeNdefMessage(message);
    if (success) {
      print('NFC Tag Written Successfully.');
    } else {
      print('Failed to write NFC tag.');
    }
  } catch (e) {
    print('Error: $e');
  }
}

你可以创建一个NfcNdefMessage对象并传递给_writeNfcTag方法:

void _createAndWriteNfcMessage() async {
  List<NfcNdefRecord> records = [
    NfcNdefRecord.createTextRecord('en', 'Hello, NFC!'),
  ];
  NfcNdefMessage message = NfcNdefMessage.from(records);

  await _writeNfcTag(message);
}

完整示例

将上述代码片段整合到一起,你将得到一个完整的Flutter应用,该应用可以检查NFC可用性,读取NFC标签,并写入NFC标签。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('NFC Manager Demo'),
        ),
        body: NfcManagerDemo(),
      ),
    );
  }
}

class NfcManagerDemo extends StatefulWidget {
  @override
  _NfcManagerDemoState createState() => _NfcManagerDemoState();
}

class _NfcManagerDemoState extends State<NfcManagerDemo> {
  bool _isNfcAvailable = false;

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

  Future<void> _checkNfcAvailability() async {
    bool isAvailable = await NfcManager.isNfcAvailable();
    if (mounted) {
      setState(() {
        _isNfcAvailable = isAvailable;
      });
    }
  }

  Future<void> _startNfcSession() async {
    try {
      if (await NfcManager.startSession()) {
        NfcManager.addNdefListener(
          onDiscovered: (NfcNdefMessage message) async {
            print('NFC Tag Discovered: $message');
            await NfcManager.stopSession();
          },
        );
      } else {
        print('Failed to start NFC session.');
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  Future<void> _writeNfcTag(NfcNdefMessage message) async {
    try {
      bool success = await NfcManager.writeNdefMessage(message);
      if (success) {
        print('NFC Tag Written Successfully.');
      } else {
        print('Failed to write NFC tag.');
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  void _createAndWriteNfcMessage() async {
    List<NfcNdefRecord> records = [
      NfcNdefRecord.createTextRecord('en', 'Hello, NFC!'),
    ];
    NfcNdefMessage message = NfcNdefMessage.from(records);
    await _writeNfcTag(message);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('NFC Available: $_isNfcAvailable'),
          if (_isNfcAvailable)
            Column(
              children: [
                ElevatedButton(
                  onPressed: () => _startNfcSession(),
                  child: Text('Start NFC Session'),
                ),
                ElevatedButton(
                  onPressed: _createAndWriteNfcMessage,
                  child: Text('Write NFC Tag'),
                ),
              ],
            )
          else
            Text('NFC is not available on this device.'),
        ],
      ),
    );
  }
}

这个示例展示了如何使用nfc_manager插件进行NFC的基本操作。你可以根据实际需求进一步扩展和优化代码。

回到顶部