flutter/lib/components/scan_util.dart
2025-07-21 15:46:30 +08:00

53 lines
1.7 KiB
Dart

import 'dart:async';
import 'package:ai_barcode_scanner/ai_barcode_scanner.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
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,
),
),
);
if (result != null && result.isNotEmpty) {
onResult(result);
}
}
}