import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; class ScanCode extends StatefulWidget { const ScanCode({super.key}); @override State createState() => _ScanCodeState(); } class _ScanCodeState extends State { Barcode? _barcode; MobileScannerController? _controller; // 添加控制器 Widget _buildBarcode(Barcode? value) { if (value == null) { return const Text('Scan something!', overflow: TextOverflow.fade, style: TextStyle(color: Colors.white)); } return Text(value.displayValue ?? 'No display value.', overflow: TextOverflow.fade, style: const TextStyle(color: Colors.white)); } bool _isScanCompleted = false; // 添加标志位 void _handleBarcode(BarcodeCapture barcodes) { if (mounted && !_isScanCompleted) { setState(() { _barcode = barcodes.barcodes.firstOrNull; print(_barcode?.displayValue); if (_barcode?.displayValue != null) { // 关闭页面并返回结果 _isScanCompleted = true; // 设置标志位为 true _controller?.stop(); // 停止扫描 Future.delayed(const Duration(milliseconds: 500), () { Get.back(result: _barcode?.displayValue); // 返回结果 }); } }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Scan Code'), ), body: Stack( children: [ MobileScanner( controller: _controller, // 传递控制器 onDetect: _handleBarcode), Align( alignment: Alignment.bottomCenter, child: Container( alignment: Alignment.bottomCenter, height: 100, padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: const Color.fromRGBO(0, 0, 0, 0.4), borderRadius: BorderRadius.circular(16), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( child: Center( child: _buildBarcode(_barcode), ), ), IconButton( icon: const Icon(Icons.close, color: Colors.white), onPressed: () { Get.back(); // 手动关闭页面 }, ), ], ), ), ), ], ), ); } }