如何使用nfc_manager读取标识符号nfc卡

问题描述 投票:0回答:2

我无法使用 nfc_manager 包读取标识符 nfc 卡。我想我需要解码标签标识符号。我的代码...

'''ValueNotifier<dynamic> result = ValueNotifier(null);'''

void _tagRead() async{
    bool isAvailable = await NfcManager.instance.isAvailable();
    NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
      result.value = tag.data;
      MifareClassic? nfca = MifareClassic.from(tag);
      var read = nfca?.identifier;
}

它返回:标识符[xxx, xx, xxx, xx](四个整数)。

flutter tags nfc
2个回答
0
投票

我使用了 nfc_manager 包,但在我的项目中也没有得到预期的结果,所以我开始使用 flutter_nfc_kit 包。只有使用“tag.id”才能访问标识符。

下面是取自示例的代码片段:https://github.com/nfcim/flutter_nfc_kit

    import 'dart:async';
    import 'dart:io' show Platform, sleep;

    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:flutter_nfc_kit/flutter_nfc_kit.dart';
    import 'package:logging/logging.dart';
    import 'package:ndef/ndef.dart' as ndef;

    class Sensors extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }

    class _MyAppState extends State<Sensors> with SingleTickerProviderStateMixin {
      String _platformVersion = '';
      NFCAvailability _availability = NFCAvailability.not_supported;
      NFCTag? _tag;
      String? _result, _writeResult;
      late TabController _tabController;
      List<ndef.NDEFRecord>? _records;

      @override
      void dispose() {
        _tabController.dispose();
        super.dispose();
      }

      @override
      void initState() {
        super.initState();
        if (!kIsWeb)
          _platformVersion =
              '${Platform.operatingSystem} ${Platform.operatingSystemVersion}';
        else
          _platformVersion = 'Web';
        initPlatformState();
        _tabController = new TabController(length: 2, vsync: this);
        _records = [];
      }

      // Platform messages are asynchronous, so we initialize in an async method.
      Future<void> initPlatformState() async {
        NFCAvailability availability;
        try {
          availability = await FlutterNfcKit.nfcAvailability;
        } on PlatformException {
          availability = NFCAvailability.not_supported;
        }

        // If the widget was removed from the tree while the asynchronous platform
        // message was in flight, we want to discard the reply rather than calling
        // setState to update our non-existent appearance.
        if (!mounted) return;

        setState(() {
          // _platformVersion = platformVersion;
          _availability = availability;
        });
      }

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('NFC Flutter Kit Example App'),
            ),
            body: Scrollbar(
                child: SingleChildScrollView(
                    child: Center(
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                  const SizedBox(height: 20),
                  Text('Running on: $_platformVersion\nNFC: $_availability'),
                  const SizedBox(height: 10),
                  ElevatedButton(
                    onPressed: () async {
                      try {
                        NFCTag tag = await FlutterNfcKit.poll();
                        setState(() {
                          _tag = tag;
                        });
                        await FlutterNfcKit.setIosAlertMessage("Working on it...");
                        if (tag.standard == "ISO 14443-4 (Type B)") {
                          String result1 =
                              await FlutterNfcKit.transceive("00B0950000");
                          String result2 = await FlutterNfcKit.transceive(
                              "00A4040009A00000000386980701");
                          setState(() {
                            _result = '1: $result1\n2: $result2\n';
                          });
                        } else if (tag.type == NFCTagType.iso18092) {
                          String result1 =
                              await FlutterNfcKit.transceive("060080080100");
                          setState(() {
                            _result = '1: $result1\n';
                          });
                        } else if (tag.type == NFCTagType.mifare_ultralight ||
                            tag.type == NFCTagType.mifare_classic ||
                            tag.type == NFCTagType.iso15693) {
                          var ndefRecords = await FlutterNfcKit.readNDEFRecords();
                          var ndefString = '';
                          for (int i = 0; i < ndefRecords.length; i++) {
                            ndefString += '${i + 1}: ${ndefRecords[i]}\n';
                          }
                          setState(() {
                            _result = ndefString;
                          });
                        } else if (tag.type == NFCTagType.webusb) {
                          var r = await FlutterNfcKit.transceive(
                              "00A4040006D27600012401");
                          print(r);
                        }
                      } catch (e) {
                        setState(() {
                          _result = 'error: $e';
                        });
                      }

                      // Pretend that we are working
                      if (!kIsWeb) sleep(new Duration(seconds: 1));
                      await FlutterNfcKit.finish(iosAlertMessage: "Finished!");
                    },
                    child: Text('Start polling'),
                  ),
                  const SizedBox(height: 10),
                  Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      child: _tag != null
                          ? Text(
                              'ID: ${_tag!.id}\nStandard: ${_tag!.standard}\nType: ${_tag!.type}\nATQA: ${_tag!.atqa}\nSAK: ${_tag!.sak}\nHistorical Bytes: ${_tag!.historicalBytes}\nProtocol Info: ${_tag!.protocolInfo}\nApplication Data: ${_tag!.applicationData}\nHigher Layer Response: ${_tag!.hiLayerResponse}\nManufacturer: ${_tag!.manufacturer}\nSystem Code: ${_tag!.systemCode}\nDSF ID: ${_tag!.dsfId}\nNDEF Available: ${_tag!.ndefAvailable}\nNDEF Type: ${_tag!.ndefType}\nNDEF Writable: ${_tag!.ndefWritable}\nNDEF Can Make Read Only: ${_tag!.ndefCanMakeReadOnly}\nNDEF Capacity: ${_tag!.ndefCapacity}\n\n Transceive Result:\n$_result')
                          : const Text('No tag polled yet.')),
                ])))),
          ),
        );
      }
    }

0
投票

如果您正在使用

nfc_manager
并且您仍然对解决方案感兴趣:

String? getIdentifier(dynamic code) {
    final ndef = Ndef.from(capture);
    if (ndef == null) throw ('Tag is not ndef.');
    return ndef.additionalData['identifier'].map((e) => e.toRadixString(16).padLeft(2, '0')).join(':').toString().toUpperCase();
}

鸣谢:https://github.com/okadan/flutter-nfc-manager/issues/89#issuecomment-1170892073

© www.soinside.com 2019 - 2024. All rights reserved.