You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Flutter nfc_manager的跨设备NFC读写异常问题求助

问题排查与修复方案

写入代码的问题

  1. 格式化标签后的逻辑错误
    当标签非NDEF格式但可格式化时,你完成了formattable?.format(message)操作,却错误设置了Tag is not ndef writable的提示,还通过errorMessage参数停止会话,这会让系统判定写入失败,实际格式化已经完成。
  2. 缺少格式化成功的分支处理
    格式化操作完成后没有正确的成功反馈,错误参数也会误导系统的会话状态。

读取代码的核心问题

读取代码直接将tag.data赋值给result,这是NFC标签的原始底层数据结构,并非解析后的NDEF文本内容。银行卡能被读取是因为其卡数据在tag.data中有可识别的固定结构,但你写入的NDEF文本必须经过专门解析才能提取内容。


修正后的写入代码

void _ndefWrite() {
  NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
    NdefMessage message = NdefMessage([
      NdefRecord.createText('Hello World!'),
    ]);

    var ndef = Ndef.from(tag);
    if (ndef == null || !ndef.isWritable) {
      final formattable = NdefFormatable.from(tag);
      if (formattable == null) {
        result.value = 'Tag cannot be formatted to NDEF';
        NfcManager.instance.stopSession(errorMessage: result.value);
        return;
      }
      try {
        await formattable.format(message);
        result.value = 'Success to format and write NDEF';
        NfcManager.instance.stopSession();
      } catch (e) {
        result.value = 'Format failed: ${e.toString()}';
        NfcManager.instance.stopSession(errorMessage: result.value);
      }
      return;
    }
    try {
      await ndef.write(message);
      result.value = 'Success to "Ndef Write"';
      NfcManager.instance.stopSession();
    } catch (e) {
      result.value = 'Write failed: ${e.toString()}';
      NfcManager.instance.stopSession(errorMessage: result.value.toString());
    }
  });
}

修正后的读取代码

void _tagRead() {
  NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
    var ndef = Ndef.from(tag);
    if (ndef == null) {
      result.value = 'Tag is not NDEF formatted';
      NfcManager.instance.stopSession();
      return;
    }
    if (ndef.cachedMessage != null) {
      NdefMessage message = ndef.cachedMessage!;
      for (var record in message.records) {
        if (record.typeNameFormat == NdefTypeNameFormat.nfcWellKnown &&
            record.type.contains('T')) {
          String text = utf8.decode(record.payload.sublist(1));
          result.value = 'Read content: $text';
          NfcManager.instance.stopSession();
          return;
        }
      }
      result.value = 'No text record found in NDEF message';
    } else {
      result.value = 'No NDEF message on tag';
    }
    NfcManager.instance.stopSession();
  });
}

额外检查项

  • 确认两台设备NFC功能正常开启,使用的是符合NFC Forum标准的可写标签(部分标签带写保护,需先解锁)。
  • 写入时保持设备与标签贴合稳定,直到收到成功提示再移开;读取时同样保持贴合至读取完成。

内容的提问来源于stack exchange,提问作者ВуDengin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 21:05:00