Flutter近场通信插件mxnfc的使用

Flutter近场通信插件mxnfc的使用

mxnfc

mxnfc 是一个用于 Flutter 应用的近场通信(NFC)插件。它允许开发者在 Android 和 iOS 设备上实现 NFC 功能。

开始使用

初始化项目

首先,确保你已经创建了一个 Flutter 项目,并且安装了 mxnfc 插件。你可以在项目的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  mxnfc: ^版本号

然后运行 flutter pub get 来获取新的依赖项。

示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 mxnfc 插件来实现 NFC 功能。

import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mxnfc/mxnfc.dart';
import 'package:mxnfc/mxnfcenum.dart';
import 'package:mxnfc/nfcresultmodel.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _mxnfcPlugin = Mxnfc.instance;
  String uuidMsg = "";

  [@override](/user/override)
  void initState() {
    super.initState();
    // 初始化平台状态
    initPlatformState();
  }

  // 平台消息初始化
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await _mxnfcPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  // NFC 读取逻辑
  void readNFC() {
    Mxnfc.instance.startScanNfc("贴近手臂顶部");
    Mxnfc.instance.onMessageRecive(
      sucCallBack: (message) {
        if (message is String) {
          print("message:$message");
          Map<String, dynamic> map = jsonDecode(message);
          if (map["key"] == "success") {
            if (map["action"] == "startScanNfc") { // 扫描开始
            } else if (map["action"] == "read") { // 读取成功
            }
          } else {
            if (map["key"] == "error") {
              if (map["action"] == "startScanNfc") { // 扫描开始
                if (map["type"] == "noSupport") { // 不支持
                } else if (map["type"] == "timeout") { // 超时
                }
              } else if (map["action"] == "read") { // 失败
              }
            }
          }
        }
      },
      errCallBack: (error) {
        print("error:$error");
      },
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('info:$uuidMsg'),
              const SizedBox(height: 50,),
              ElevatedButton(
                onPressed: () {
                  Mxnfc.instance.closeNFCMessage();
                  setState(() {
                    uuidMsg = "";
                  });
                },
                child: const Text("关闭NFC"),
              ),
              ElevatedButton(
                onPressed: () {
                  Mxnfc.instance.openNFCSettings();
                },
                child: const Text("去打开NFC"),
              ),
              ElevatedButton(
                onPressed: () async {
                  int state = await Mxnfc.instance.getNFCSwitchState();
                  print("我的开关状态:$state");
                  setState(() {
                    uuidMsg = "$state";
                  });
                },
                child: const Text("开关状态"),
              ),
              ElevatedButton(
                onPressed: () {
                  Mxnfc.instance.scanNfc(
                    message: "贴近手臂底部",
                    successCallBack: (m) {
                      if (m is NFCResultModel) {
                        print(">>m:${m.msg}");
                        setState(() {
                          uuidMsg = m.sectionInfo ?? "";
                        });
                      }
                    },
                    failedCallBack: (m) {
                      if (m is NFCResultModel) {
                        if (m.resultType == NFCScanResult.isOpen) {
                          Mxnfc.instance.settNFCBecomeEnableForeground();
                        } else if (m.resultType == NFCScanResult.isNotOpen) {
                          singleButtonDialog(content: "去设置", mycontext: context);
                        } else {
                          NFCResultModel m1 = m;
                          print(">>m:$m1 type:${m1.resultType}");
                          setState(() {
                            uuidMsg = m1.msg;
                          });
                        }
                      }
                    },
                  );
                },
                child: const Text("开始扫描"),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          child: const Text("开始扫描"),
          onPressed: () {
            readNFC();
          },
        ),
      ),
    );
  }

  /// 单个按钮对话框
  void singleButtonDialog({
    String title = "124",
    TextAlign titleAlign = TextAlign.center,
    Color titleColor = const Color.fromARGB(155, 155, 155, 1),
    bool barrierDismissible = true,
    required String content,
    Function()? confirmCallBack,
    TextAlign textAlign = TextAlign.start,
    Color confirmTitleColor = const Color.fromARGB(155, 155, 155, 1),
    String confirmButtonTitle = "确定",
    required BuildContext mycontext,
  }) {
    showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Container(
            padding: const EdgeInsets.only(bottom: 16),
            child: Text(title,
                textAlign: titleAlign,
                style: TextStyle(color: titleColor, fontSize: 32)),
          ),
          content: Text(content,
              textAlign: textAlign,
              style: TextStyle(color: titleColor, fontSize: 30)),
          actions: [
            CupertinoDialogAction(
              onPressed: () {
                if (confirmCallBack != null) {
                  confirmCallBack();
                }
              },
              child: Text(confirmButtonTitle,
                  style: TextStyle(
                      color: confirmTitleColor,
                      fontSize: 32,
                      fontWeight: FontWeight.bold)),
            ),
          ],
        );
      },
    );
  }
}

更多关于Flutter近场通信插件mxnfc的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter近场通信插件mxnfc的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现近场通信(NFC)功能,可以使用第三方插件 mxnfc。以下是如何使用 mxnfc 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 mxnfc 依赖:

dependencies:
  flutter:
    sdk: flutter
  mxnfc: ^1.0.0  # 请根据实际版本号进行替换

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

2. 配置 Android 和 iOS

Android

AndroidManifest.xml 文件中添加 NFC 权限:

<uses-permission android:name="android.permission.NFC" />

iOS

Info.plist 文件中添加 NFC 权限描述:

<key>NFCReaderUsageDescription</key>
<string>We need access to NFC to read tags.</string>

3. 使用 mxnfc 插件

在你的 Dart 文件中导入 mxnfc 插件,并开始使用它。

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

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _nfcData = "未读取到NFC数据";

  [@override](/user/override)
  void initState() {
    super.initState();
    _initNFC();
  }

  Future<void> _initNFC() async {
    try {
      MxNfc nfc = MxNfc();
      nfc.onTagDiscovered().listen((tag) {
        setState(() {
          _nfcData = "NFC数据: $tag";
        });
      });
    } catch (e) {
      setState(() {
        _nfcData = "NFC初始化失败: $e";
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('NFC示例'),
        ),
        body: Center(
          child: Text(_nfcData),
        ),
      ),
    );
  }
}
回到顶部