flutter/lib/components/scan_util.dart

77 lines
2.6 KiB
Dart
Raw Normal View History

2025-07-21 15:46:30 +08:00
import 'dart:async';
import 'package:ai_barcode_scanner/ai_barcode_scanner.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
2025-08-21 10:50:38 +08:00
import 'package:permission_handler/permission_handler.dart';
2025-07-21 15:46:30 +08:00
class ScanUtil {
static Future<void> openScanner({required void Function(String) onResult}) async {
final controller = MobileScannerController();
bool hasHandled = false;
bool validator(BarcodeCapture capture) {
final code = capture.barcodes.isNotEmpty ? capture.barcodes.first.rawValue : null;
return code != null && code.isNotEmpty;
}
final result = await Get.to<String>(
() => AiBarcodeScanner(
controller: controller,
galleryButtonText: '从相册选择',
galleryButtonAlignment: const Alignment(0.0, 0.7),
validator: validator,
onDetect: (capture) {
if (hasHandled) return;
final code = capture.barcodes.isNotEmpty ? capture.barcodes.first.rawValue : null;
if (code != null && code.isNotEmpty) {
hasHandled = true;
Get.back(result: code);
}
},
overlayConfig: const ScannerOverlayConfig(
scannerBorder: ScannerBorder.corner,
borderColor: Colors.greenAccent,
successColor: Colors.lightGreenAccent,
errorColor: Colors.redAccent,
borderRadius: 24,
cornerLength: 60,
scannerAnimation: ScannerAnimation.fullWidth,
),
scanWindow: Rect.fromCenter(
center: MediaQuery.of(Get.context!).size.center(Offset.zero),
width: MediaQuery.of(Get.context!).size.width * 0.8,
height: MediaQuery.of(Get.context!).size.height * 0.5,
),
2025-08-21 10:50:38 +08:00
// 异常处理
errorBuilder: (context, error) {
String message = "无法启动摄像头,请检查权限";
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error, color: Colors.red, size: 60),
const SizedBox(height: 16),
Text(
message,
style: const TextStyle(fontSize: 18, color: Colors.red),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () async => await openAppSettings(),
child: const Text('去开启权限'),
),
],
),
);
},
2025-07-21 15:46:30 +08:00
),
);
if (result != null && result.isNotEmpty) {
onResult(result);
}
}
}