我正在构建一个应用程序,要求我将 nfc 标签上写入的文本显示为人类可读的字符串。我目前正在使用 nfc_manager 这是我在应用程序中收到的响应的屏幕截图,它是 json:
{iso15693: {identifier: [224, 4, 1, 8, 62, 149, 102, 100], icManufacturerCode: 4, icSerialNumber: [1, 8, 62, 149, 102, 100]}, ndef: {cachedMessage: {records: [payload: [2, 101, 110, 65, 100, 97, 109], typeNameFormat: 1, identifier: [], type: [84]}]}, isWritable: true, maxSize: 312}}
我的代码如下:
class NFC_scanner extends StatefulWidget {
const NFC_scanner({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => MyNFCState();
}
class MyNFCState extends State<NFC_scanner> {
ValueNotifier<dynamic> result = ValueNotifier(null);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('NfcManager Plugin Example'),
backgroundColor: Colors.transparent,
foregroundColor: Colors.lightGreen,
elevation: 0.0,
),
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(shape: BoxShape.circle),
child: SingleChildScrollView(
child: ValueListenableBuilder<dynamic>(
valueListenable: result,
builder: (context, value, _) =>
Container(
height: 200,
width: 200,
child: Text('${value ?? ''}')
),
),
),
),
),
Container(
height: 300,
width: 300,
child: Lottie.network('https://lottie.host/124ecd28-8486-478f-a479-4fa22242dda5/ycBN8Sr5aP.json')
),
Text('Please keep your device near your phone'),
SizedBox(height: 100),
FloatingActionButton(
onPressed: _tagRead,
backgroundColor: Colors.lightGreen,
child: Icon(
Icons.zoom_in,
),
)
],
),
),
),
),
);
}
void _tagRead() async {
showDialog(
context: context,
builder: (context) {
return AlertDialog(content: Text('You can tap the tag now !'));
});
try {
await NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
result.value = tag.data;
print('tag.data: ${tag.data}');
NfcManager.instance.stopSession();
});
} catch (e) {
result.value = e.toString();
}
}
}
我尝试解析 json 响应,但无法使用 stackoverflow 中的以下代码获取需要转换为字符串的有效负载值:
NfcManager.instance.startSession(onDiscovered : (NfcTag tag) async{
var payload = tag.data["ndef"]["cachedMessage"]["record"][0]["payload"];
// now convert that payload into string
var stringPayload = String.fromCharCodes(payload);
}
每当我运行它时,它都会阻止 NFC 标签读取。
提前感谢您的帮助
这不是对您如何解决 Dart/Flutter 问题的答案,而是帮助您编码。
您的有效负载是一条 NDEF 消息,可能包含多个 NDEF 记录。
在您的情况下,您的有效负载(十进制)是“2, 101, 110, 65, 100, 97, 109”。请谷歌搜索“NDEF消息和记录”以了解NDEF消息是如何构造的。
正如@Andrew 已经评论的那样,您要查找的内容有一个尾随“2”,后跟“101、110、65、100、97、109”。
使用在线“十进制到文本”转换器,例如https://www.browserling.com/tools/decimal-to-text并使用这些不带逗号的数字:“101 110 65 100 97 109”将为您提供以下结果:
en亚当.
结尾的“en”是语言代码,后面是从标签中读取的文本:“Adam”。