cage_change_page.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import 'package:chicken_farm/core/utils/logger.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:chicken_farm/components/vb_app_bar.dart';
  4. import 'package:chicken_farm/core/utils/toast.dart';
  5. import 'package:chicken_farm/core/services/pda/scan_channel.dart';
  6. import 'package:chicken_farm/components/vb_rfid_field.dart';
  7. class CageChangePage extends StatefulWidget {
  8. const CageChangePage({super.key});
  9. @override
  10. State<CageChangePage> createState() => _CageChangePageState();
  11. }
  12. class _CageChangePageState extends State<CageChangePage> {
  13. final List<String> _rfids = [];
  14. // 添加TextEditingControllers用于控制输入框
  15. final TextEditingController _sourceCageController = TextEditingController();
  16. final TextEditingController _targetCageController = TextEditingController();
  17. // 添加FocusNode用于控制焦点
  18. final FocusNode _sourceCageFocusNode = FocusNode();
  19. final FocusNode _targetCageFocusNode = FocusNode();
  20. // 扫描状态
  21. bool _isScanningSource = false;
  22. bool _isScanningTarget = false;
  23. int _scanTag = 1;
  24. @override
  25. void initState() {
  26. super.initState();
  27. _sourceCageController.clear();
  28. _targetCageController.clear();
  29. // 监听焦点变化以更新_scanTag值
  30. _sourceCageFocusNode.addListener(() {
  31. if (_sourceCageFocusNode.hasFocus) {
  32. _scanTag = 1;
  33. }
  34. });
  35. _targetCageFocusNode.addListener(() {
  36. if (_targetCageFocusNode.hasFocus) {
  37. _scanTag = 2;
  38. }
  39. });
  40. ScanChannel.openScanHead().then((success) {
  41. if (success) {
  42. logger.d("扫描头已打开");
  43. } else {
  44. logger.d("扫描头打开失败");
  45. }
  46. });
  47. // 初始化监听
  48. ScanChannel.initScanListener(
  49. onScanResult: (result) {
  50. if (_scanTag == 1) {
  51. // 源笼号
  52. setState(() {
  53. _sourceCageController.text = result;
  54. _isScanningSource = false;
  55. });
  56. if (_targetCageController.text.isEmpty) {
  57. // 源笼号扫描成功后自动延时扫描目标笼号
  58. ScanChannel.stopSingleScan();
  59. logger.d("自动扫描目标笼号");
  60. _targetCageFocusNode.requestFocus();
  61. _dealyScanCode(2);
  62. }
  63. } else if (_scanTag == 2) {
  64. // 目标笼号
  65. setState(() {
  66. _targetCageController.text = result;
  67. _isScanningTarget = false;
  68. });
  69. }
  70. // 扫码成功后停止解码(保留扫描头)
  71. ScanChannel.stopSingleScan();
  72. },
  73. onScanError: (error) {
  74. logger.d("扫码错误:$error");
  75. setState(() {
  76. _isScanningSource = false;
  77. });
  78. },
  79. onKeyPress: (bool isDouble, String keyCode) {
  80. if (isDouble && keyCode == "KEY_619") {
  81. _sourceCageController.clear();
  82. _targetCageController.clear();
  83. _scanTag = 1;
  84. ScanChannel.startScan();
  85. } else {
  86. logger.d("按键:$isDouble $keyCode");
  87. }
  88. },
  89. );
  90. _scanTag = 1;
  91. // 进入页面默认使原笼号获取到焦点
  92. // WidgetsBinding.instance.addPostFrameCallback((_) {
  93. // _sourceCageFocusNode.requestFocus();
  94. // });
  95. }
  96. @override
  97. void dispose() {
  98. // 释放TextEditingControllers
  99. _sourceCageController.dispose();
  100. _targetCageController.dispose();
  101. // 释放FocusNode
  102. _sourceCageFocusNode.dispose();
  103. _targetCageFocusNode.dispose();
  104. // 手动关闭扫描头,立即释放资源
  105. ScanChannel.closeScanHead();
  106. // 释放通道
  107. ScanChannel.dispose();
  108. super.dispose();
  109. }
  110. @override
  111. Widget build(BuildContext context) {
  112. return Scaffold(
  113. appBar: const VberAppBar(title: '换笼管理', showLeftButton: true),
  114. body: SingleChildScrollView(
  115. child: Padding(
  116. padding: const EdgeInsets.all(16.0),
  117. child: Column(
  118. crossAxisAlignment: CrossAxisAlignment.start,
  119. children: [
  120. // 源笼号区域
  121. _buildCageSection(1),
  122. const SizedBox(height: 15),
  123. // 目标笼号区域
  124. _buildCageSection(2),
  125. const SizedBox(height: 15),
  126. // 电子编号区域
  127. _buildRfidSection(),
  128. const SizedBox(height: 15),
  129. // 提交按钮
  130. SizedBox(
  131. width: double.infinity,
  132. child: ElevatedButton(
  133. onPressed:
  134. _sourceCageController.text.isNotEmpty &&
  135. _targetCageController.text.isNotEmpty &&
  136. _rfids.isNotEmpty
  137. ? _handleSubmit
  138. : null,
  139. style: ElevatedButton.styleFrom(
  140. backgroundColor:
  141. (_sourceCageController.text.isNotEmpty &&
  142. _targetCageController.text.isNotEmpty &&
  143. _rfids.isNotEmpty)
  144. ? Colors.blue
  145. : Colors.grey,
  146. foregroundColor: Colors.white,
  147. ),
  148. child: const Text('提交'),
  149. ),
  150. ),
  151. const SizedBox(height: 20),
  152. // 已识别的电子编号列表
  153. if (_rfids.isNotEmpty) ...[
  154. Row(
  155. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  156. children: [
  157. const Text(
  158. '已识别的电子编号',
  159. style: TextStyle(fontWeight: FontWeight.bold),
  160. ),
  161. IconButton(
  162. icon: const Icon(Icons.clear, size: 18),
  163. onPressed: _clearRfids,
  164. tooltip: '清空编号',
  165. ),
  166. ],
  167. ),
  168. const SizedBox(height: 10),
  169. Container(
  170. padding: const EdgeInsets.all(10),
  171. decoration: BoxDecoration(
  172. border: Border.all(color: Colors.grey),
  173. borderRadius: BorderRadius.circular(8),
  174. ),
  175. child: ListView.builder(
  176. shrinkWrap: true,
  177. physics: const NeverScrollableScrollPhysics(),
  178. padding: EdgeInsets.zero,
  179. itemCount: _rfids.length,
  180. itemBuilder: (context, index) {
  181. return ListTile(
  182. visualDensity: VisualDensity.compact,
  183. contentPadding: const EdgeInsets.symmetric(
  184. horizontal: 2,
  185. vertical: 0,
  186. ),
  187. title: Text(_rfids[index]),
  188. trailing: IconButton(
  189. icon: const Icon(
  190. Icons.delete,
  191. size: 18,
  192. color: Colors.red,
  193. ),
  194. onPressed: () => _removeRfid(index),
  195. ),
  196. );
  197. },
  198. ),
  199. ),
  200. ],
  201. const SizedBox(height: 20),
  202. ],
  203. ),
  204. ),
  205. ),
  206. );
  207. }
  208. Widget _buildCageSection(int tag) {
  209. String title = '源笼号';
  210. TextEditingController controller = _sourceCageController;
  211. FocusNode focusNode = _sourceCageFocusNode;
  212. bool isScanning = _isScanningSource;
  213. if (tag != 1) {
  214. tag = 2;
  215. title = '目标笼号';
  216. controller = _targetCageController;
  217. focusNode = _targetCageFocusNode;
  218. isScanning = _isScanningTarget;
  219. }
  220. // 确保光标在文本末尾
  221. if (controller.text.isNotEmpty) {
  222. controller.selection = TextSelection.fromPosition(
  223. TextPosition(offset: controller.text.length),
  224. );
  225. }
  226. return Column(
  227. crossAxisAlignment: CrossAxisAlignment.start,
  228. children: [
  229. Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
  230. const SizedBox(height: 10),
  231. Container(
  232. padding: const EdgeInsets.fromLTRB(16, 2, 16, 2),
  233. decoration: BoxDecoration(
  234. border: Border.all(color: Colors.grey),
  235. borderRadius: BorderRadius.circular(8),
  236. ),
  237. child: Row(
  238. children: [
  239. Expanded(
  240. // 将Text替换为TextField
  241. child: TextField(
  242. focusNode: focusNode,
  243. controller: controller,
  244. enabled: controller.text.isEmpty,
  245. decoration: InputDecoration(
  246. border: InputBorder.none,
  247. hintText: controller.text.isNotEmpty ? null : '未扫描',
  248. hintStyle: TextStyle(
  249. color: controller.text.isNotEmpty
  250. ? Colors.black
  251. : Colors.grey,
  252. fontSize: 16,
  253. ),
  254. ),
  255. style: TextStyle(
  256. color: controller.text.isNotEmpty
  257. ? Colors.black
  258. : Colors.grey,
  259. fontSize: 16,
  260. ),
  261. onChanged: (text) {
  262. setState(() {
  263. // 文本更改由controller自动处理
  264. });
  265. },
  266. ),
  267. ),
  268. if (controller.text.isNotEmpty) ...[
  269. IconButton(
  270. icon: const Icon(Icons.refresh, size: 20),
  271. onPressed: () {
  272. _handleChangeCageCode(tag);
  273. },
  274. ),
  275. ] else ...[
  276. IconButton(
  277. icon: isScanning
  278. ? const SizedBox(
  279. width: 20,
  280. height: 20,
  281. child: CircularProgressIndicator(strokeWidth: 2),
  282. )
  283. : const Icon(Icons.qr_code_scanner, size: 20),
  284. onPressed: () {
  285. _handleScanCageCode(tag);
  286. },
  287. ),
  288. ],
  289. ],
  290. ),
  291. ),
  292. ],
  293. );
  294. }
  295. Widget _buildRfidSection() {
  296. return VberRfidField(
  297. rfids: _rfids,
  298. onRfidScanned: (rfid) {
  299. // 检查是否已存在相同的RFID标签
  300. bool isDuplicate = _rfids.any((existingRfid) => existingRfid == rfid);
  301. if (isDuplicate) {
  302. ToastUtil.info("电子编号已存在");
  303. } else {
  304. // 如果不重复,添加到列表中
  305. setState(() {
  306. _rfids.insert(0, rfid);
  307. });
  308. ToastUtil.success("成功添加新的电子编号");
  309. }
  310. },
  311. multiple: true,
  312. multipleScan: false,
  313. label: '电子编号',
  314. multiplePlaceholder: '未识别',
  315. multipleFormat: '已识别 %d 枚电子编号',
  316. );
  317. }
  318. void _dealyScanCode(int scanTag, {int? dealy}) async {
  319. dealy ??= 800;
  320. _scanTag = scanTag;
  321. logger.d("开始扫码: $_scanTag");
  322. await Future.delayed(Duration(milliseconds: dealy));
  323. bool success = await ScanChannel.startScan();
  324. if (!success) {
  325. ToastUtil.error("扫码失败");
  326. }
  327. }
  328. void _handleScanCageCode(int tag) async {
  329. if (_isScanningTarget || _isScanningSource) return;
  330. setState(() {
  331. if (tag == 1) {
  332. _isScanningSource = true;
  333. } else if (tag == 2) {
  334. _isScanningTarget = true;
  335. }
  336. });
  337. _scanTag = tag;
  338. logger.d("开始扫码: $_scanTag");
  339. bool success = await ScanChannel.startScan();
  340. if (!success) {
  341. ToastUtil.error("扫码失败");
  342. }
  343. }
  344. void _handleChangeCageCode(int tag) {
  345. setState(() {
  346. if (tag == 1) {
  347. _sourceCageController.clear();
  348. } else {
  349. _targetCageController.clear();
  350. }
  351. });
  352. _dealyScanCode(tag);
  353. }
  354. // 移除指定索引的电子编号
  355. void _removeRfid(int index) {
  356. setState(() {
  357. _rfids.removeAt(index);
  358. });
  359. }
  360. // 清空所有已识别的电子编号
  361. void _clearRfids() {
  362. setState(() {
  363. _rfids.clear();
  364. });
  365. ToastUtil.info('已清空所有电子编号');
  366. }
  367. // 提交数据
  368. void _handleSubmit() {
  369. // 在实际应用中,这里会发送数据到服务器
  370. ScaffoldMessenger.of(context).showSnackBar(
  371. const SnackBar(content: Text('换笼操作提交成功'), backgroundColor: Colors.green),
  372. );
  373. for (var rfid in _rfids) {
  374. logger.d('提交电子编号: $rfid');
  375. }
  376. // 提交后重置表单
  377. setState(() {
  378. _sourceCageController.clear();
  379. _targetCageController.clear();
  380. _rfids.clear();
  381. });
  382. }
  383. }