flutter_nfc_kit icon indicating copy to clipboard operation
flutter_nfc_kit copied to clipboard

How to read sector data

Open laterdayi opened this issue 10 months ago • 3 comments

Currently, the data read is limited, and the data in the sector cannot be retrieved

Image

i hope get

Image

laterdayi avatar Feb 11 '25 10:02 laterdayi

I am afraid we do not provide any data in MifareInfo, only metadata. If you would like to read Mifare Classic tags, you can use readBlock or readSector from FlutterNfcKit class.

Harry-Chen avatar Feb 11 '25 15:02 Harry-Chen

Whether you can add the corresponding demo to the document or example to obtain the data in the block

maxfrees avatar Feb 11 '25 15:02 maxfrees

Is this a possible example @maxfrees ? I've used a similar method in my app to read an uuid that i write with another method created by me. If you want i can implement simple methods to write and read to the tag directly in the package

import 'dart:convert';
import 'package:flutter_nfc_kit/flutter_nfc_kit.dart';

Future<String> readNfcDataFromTag(NFCTag tag, int bytesToRead) async {
  if (tag.type != NFCTagType.mifare_classic) {
    throw DisplayableException('Unknown tag type.');
  }

  final int neededBlocks = (bytesToRead / 16).ceil();
  final List<int> allBytes = [];
  int blocksRead = 0;

  for (int sector = 1; blocksRead < neededBlocks; sector++) {
    const String factoryKeyA = 'FFFFFFFFFFFF';

    final bool authOk = await FlutterNfcKit.authenticateSector(
      sector,
      keyA: factoryKeyA,
    );
    if (!authOk) {
      throw Exception('Failed to authenticate $sector sector');
    }

    for (int block = 0; block < 4 && blocksRead < neededBlocks; block++) {
      final int blockIndex = sector * 4 + block;
      final Uint8List blockData = await FlutterNfcKit.readBlock(blockIndex);
      allBytes.addAll(blockData);
      blocksRead++;

      if (allBytes.length >= bytesToRead) break;
    }
  }

  final List<int> payload = allBytes.take(bytesToRead).toList();
  return utf8.decode(payload);
}

albertoboccolini avatar Jun 16 '25 20:06 albertoboccolini