Files
Base-QR-FlutterApp/lib/screens/scanner_screen.dart
T
2026-06-19 08:57:58 -06:00

903 lines
26 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:qrscanner/models/auth_session.dart';
import 'package:qrscanner/models/pass_code.dart';
import 'package:qrscanner/models/scan_response.dart';
import 'package:qrscanner/services/feedback_service.dart';
import 'package:qrscanner/services/hardware_scanner_service.dart';
import 'package:qrscanner/services/pass_code_service.dart';
import 'package:qrscanner/theme/app_theme.dart';
enum _ScanPhase { scanning, processing, success, warning }
enum _ScannerInput { loading, camera, hardware }
const double _scanWindowSize = 260;
const double _scanWindowRadius = 28;
const Alignment _scanWindowAlignment = Alignment(0, -0.12);
const Duration _resultDisplayDuration = Duration(seconds: 5);
class ScannerScreen extends StatefulWidget {
const ScannerScreen({
super.key,
required this.session,
this.initialCode,
});
final AuthSession session;
final String? initialCode;
@override
State<ScannerScreen> createState() => _ScannerScreenState();
}
class _ScannerScreenState extends State<ScannerScreen>
with TickerProviderStateMixin {
MobileScannerController? _cameraController;
final _hardwareScanner = HardwareScannerService.instance;
final _passCodeService = PassCodeService();
final _feedbackService = FeedbackService();
_ScannerInput _inputMode = _ScannerInput.loading;
bool _hardwareAvailable = false;
bool _isInitialSetup = true;
bool _isSwitchingInput = false;
_ScanPhase _phase = _ScanPhase.scanning;
bool _isHandlingDetection = false;
String? _lastScannedCode;
String? _message;
PassCode? _passCode;
Timer? _resultAutoDismissTimer;
late final AnimationController _scanLineController;
late final AnimationController _resultController;
late final Animation<double> _scanLineAnimation;
late final Animation<double> _scaleAnimation;
late final Animation<Offset> _arrowSlide;
@override
void initState() {
super.initState();
_scanLineController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 2400),
)..repeat();
_scanLineAnimation = CurvedAnimation(
parent: _scanLineController,
curve: Curves.easeInOut,
);
_resultController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 700),
);
_scaleAnimation = CurvedAnimation(
parent: _resultController,
curve: Curves.elasticOut,
);
_arrowSlide = Tween<Offset>(
begin: const Offset(0, -0.35),
end: Offset.zero,
).animate(CurvedAnimation(
parent: _resultController,
curve: Curves.easeOutBack,
));
_initializeScannerInput();
}
Future<void> _initializeScannerInput() async {
_hardwareAvailable = await HardwareScannerService.isAvailable();
if (!mounted) return;
if (_hardwareAvailable) {
await _activateHardwareMode(showLoading: true);
} else {
await _activateCameraMode(showLoading: true);
}
final pendingCode = widget.initialCode?.trim();
if (!mounted || pendingCode == null || pendingCode.isEmpty) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _processScan(pendingCode);
});
}
MobileScannerController _createCameraController() {
return MobileScannerController(
autoStart: false,
detectionSpeed: DetectionSpeed.normal,
detectionTimeoutMs: 500,
facing: CameraFacing.back,
formats: const [BarcodeFormat.qrCode],
autoZoom: true,
);
}
Future<void> _activateHardwareMode({bool showLoading = false}) async {
if (!mounted) return;
if (showLoading) {
setState(() => _inputMode = _ScannerInput.loading);
}
try {
try {
await _cameraController?.stop();
} catch (_) {}
await _cameraController?.dispose();
_cameraController = null;
_scanLineController.stop();
await Future<void>.delayed(const Duration(milliseconds: 300));
final started = await _hardwareScanner.activate(onScan: _onRawScan);
if (!mounted) return;
if (started) {
setState(() {
_inputMode = _ScannerInput.hardware;
_isInitialSetup = false;
});
return;
}
await _activateCameraMode(
showLoading: showLoading,
fallbackFromHardware: true,
);
} finally {
if (mounted && _inputMode == _ScannerInput.loading) {
setState(() {
_inputMode = _ScannerInput.hardware;
_isInitialSetup = false;
});
}
}
}
Future<void> _activateCameraMode({
bool showLoading = false,
bool fallbackFromHardware = false,
}) async {
if (!mounted) return;
if (showLoading) {
setState(() => _inputMode = _ScannerInput.loading);
}
try {
await _hardwareScanner.pause();
await Future<void>.delayed(const Duration(milliseconds: 300));
try {
await _cameraController?.stop();
} catch (_) {}
await _cameraController?.dispose();
_cameraController = _createCameraController();
if (!_scanLineController.isAnimating) {
_scanLineController.repeat();
}
if (!mounted) return;
setState(() {
_inputMode = _ScannerInput.camera;
_isInitialSetup = false;
});
await Future<void>.delayed(const Duration(milliseconds: 200));
try {
await _cameraController!.start();
} catch (_) {
if (!mounted) return;
if (!fallbackFromHardware) {
await _activateHardwareMode();
}
}
} finally {
if (mounted && _inputMode == _ScannerInput.loading) {
setState(() {
_inputMode = _ScannerInput.camera;
_isInitialSetup = false;
});
}
}
}
Future<void> _toggleScannerInput() async {
if (!_hardwareAvailable ||
_phase != _ScanPhase.scanning ||
_isSwitchingInput ||
_inputMode == _ScannerInput.loading) {
return;
}
setState(() => _isSwitchingInput = true);
try {
if (_inputMode == _ScannerInput.hardware) {
await _activateCameraMode();
} else if (_inputMode == _ScannerInput.camera) {
await _activateHardwareMode();
}
} finally {
if (mounted) {
setState(() => _isSwitchingInput = false);
} else {
_isSwitchingInput = false;
}
}
}
bool get _showsScannerInput =>
_phase == _ScanPhase.scanning ||
_phase == _ScanPhase.processing ||
_phase == _ScanPhase.success ||
_phase == _ScanPhase.warning;
Rect _scanWindowRect(Size size) {
final center = _scanWindowAlignment.alongSize(size);
return Rect.fromCenter(
center: center,
width: _scanWindowSize,
height: _scanWindowSize,
);
}
void _cancelAutoDismiss() {
_resultAutoDismissTimer?.cancel();
_resultAutoDismissTimer = null;
}
void _scheduleAutoDismiss() {
_cancelAutoDismiss();
_resultAutoDismissTimer = Timer(_resultDisplayDuration, () {
if (!mounted) return;
if (_phase == _ScanPhase.success || _phase == _ScanPhase.warning) {
unawaited(_scanAgain());
}
});
}
@override
void dispose() {
_cancelAutoDismiss();
_scanLineController.dispose();
_resultController.dispose();
_cameraController?.dispose();
_hardwareScanner.deactivate();
_feedbackService.dispose();
super.dispose();
}
void _onRawScan(String rawValue) {
_processScan(rawValue);
}
Future<void> _onDetect(BarcodeCapture capture) async {
final rawValue = capture.barcodes.firstOrNull?.rawValue?.trim();
if (rawValue == null || rawValue.isEmpty) return;
await _processScan(rawValue);
}
Future<void> _processScan(String rawValue) async {
if (_isHandlingDetection || _phase == _ScanPhase.processing) return;
final code = _extractCode(rawValue);
if (code.isEmpty) return;
final showingResult =
_phase == _ScanPhase.success || _phase == _ScanPhase.warning;
if (showingResult) {
_cancelAutoDismiss();
_resultController.reset();
} else {
if (_phase != _ScanPhase.scanning) return;
if (code == _lastScannedCode) return;
}
_isHandlingDetection = true;
setState(() {
_phase = _ScanPhase.processing;
_lastScannedCode = code;
_message = null;
_passCode = null;
});
_scanLineController.stop();
if (_inputMode == _ScannerInput.camera) {
await _cameraController?.stop();
}
await _feedbackService.onCodeDetected();
try {
final response = await _passCodeService.scan(
session: widget.session,
code: code,
);
if (!mounted) return;
await _showResult(response);
} catch (_) {
if (!mounted) return;
await _showResult(
const ScanResponse(
success: false,
message: 'No se pudo validar el código. Revisa la conexión.',
),
);
} finally {
_isHandlingDetection = false;
}
}
String _extractCode(String rawValue) {
final uri = Uri.tryParse(rawValue);
if (uri != null) {
final queryCode = uri.queryParameters['code'];
if (queryCode != null && queryCode.isNotEmpty) return queryCode;
final segments = uri.pathSegments.where((s) => s.isNotEmpty).toList();
if (segments.isNotEmpty) return segments.last;
}
return rawValue;
}
Future<void> _showResult(ScanResponse response) async {
_resultController.reset();
setState(() {
_message = response.message;
_passCode = response.passCode;
_phase = response.success ? _ScanPhase.success : _ScanPhase.warning;
});
if (response.success) {
await _feedbackService.onSuccess();
} else {
await _feedbackService.onWarning();
}
await _resultController.forward();
_scheduleAutoDismiss();
if (_inputMode == _ScannerInput.camera) {
await _cameraController?.start();
}
}
Future<void> _scanAgain() async {
_cancelAutoDismiss();
_resultController.reset();
_isHandlingDetection = false;
setState(() {
_phase = _ScanPhase.scanning;
_lastScannedCode = null;
_message = null;
_passCode = null;
});
if (_inputMode == _ScannerInput.camera) {
_scanLineController.repeat();
await _cameraController?.start();
}
}
@override
Widget build(BuildContext context) {
final isSuccess = _phase == _ScanPhase.success;
final isWarning = _phase == _ScanPhase.warning;
final overlayColor = isSuccess
? AppTheme.success.withValues(alpha: 0.82)
: isWarning
? AppTheme.warning.withValues(alpha: 0.82)
: Colors.transparent;
return Scaffold(
backgroundColor: Colors.black,
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back_rounded),
onPressed: () => Navigator.of(context).pop(),
),
title: const Text('Escanear pase'),
centerTitle: true,
actions: [
if (_hardwareAvailable && _phase == _ScanPhase.scanning)
IconButton(
tooltip: _inputMode == _ScannerInput.hardware
? 'Usar cámara'
: 'Usar escáner Honeywell',
icon: _isSwitchingInput
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: Icon(
_inputMode == _ScannerInput.hardware
? Icons.camera_alt_outlined
: Icons.barcode_reader,
),
onPressed: _isSwitchingInput ? null : _toggleScannerInput,
),
],
),
body: Stack(
fit: StackFit.expand,
children: [
if (_inputMode == _ScannerInput.loading && _isInitialSetup)
const Center(
child: CircularProgressIndicator(color: AppTheme.primary),
),
if (_showsScannerInput &&
_inputMode == _ScannerInput.camera &&
_cameraController != null)
LayoutBuilder(
builder: (context, constraints) {
final scanRect = _scanWindowRect(constraints.biggest);
return MobileScanner(
controller: _cameraController!,
onDetect: _onDetect,
scanWindow: scanRect,
overlayBuilder: (context, constraints) {
if (_phase != _ScanPhase.scanning) {
return const SizedBox.shrink();
}
return AnimatedBuilder(
animation: _scanLineAnimation,
builder: (context, child) {
return CustomPaint(
size: constraints.biggest,
painter: _ScannerOverlayPainter(
scanRect: scanRect,
scanLineProgress: _scanLineAnimation.value,
),
);
},
);
},
);
},
),
if (_showsScannerInput && _inputMode == _ScannerInput.hardware)
_buildHardwareScannerView(),
AnimatedContainer(
duration: const Duration(milliseconds: 450),
curve: Curves.easeOutCubic,
color: overlayColor,
),
if (_phase == _ScanPhase.processing)
SafeArea(
child: Center(child: _buildProcessingCard()),
),
if (_phase == _ScanPhase.success || _phase == _ScanPhase.warning)
SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(vertical: 16),
child: _buildResultCard(),
),
),
),
if (_phase == _ScanPhase.scanning && _inputMode != _ScannerInput.loading)
SafeArea(
child: Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.fromLTRB(32, 0, 32, 28),
child: _buildHint(),
),
),
),
],
),
);
}
Widget _buildProcessingCard() {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 28),
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 28),
decoration: BoxDecoration(
color: AppTheme.surfaceDark.withValues(alpha: 0.92),
borderRadius: BorderRadius.circular(24),
border: Border.all(color: Colors.white.withValues(alpha: 0.08)),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(
width: 42,
height: 42,
child: CircularProgressIndicator(
strokeWidth: 3,
color: AppTheme.primary,
),
),
const SizedBox(height: 18),
Text(
'Validando código...',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
if (_lastScannedCode != null) ...[
const SizedBox(height: 8),
Text(
_lastScannedCode!,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.45),
letterSpacing: 1.2,
),
),
],
],
),
);
}
Widget _buildResultCard() {
final isSuccess = _phase == _ScanPhase.success;
final accent = isSuccess ? AppTheme.success : AppTheme.warning;
final accentDark = isSuccess ? AppTheme.successDark : AppTheme.warningDark;
return FadeTransition(
opacity: _scaleAnimation,
child: ScaleTransition(
scale: _scaleAnimation,
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 24),
padding: const EdgeInsets.fromLTRB(24, 32, 24, 24),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
accent.withValues(alpha: 0.95),
accentDark.withValues(alpha: 0.95),
],
),
borderRadius: BorderRadius.circular(28),
boxShadow: [
BoxShadow(
color: accent.withValues(alpha: 0.45),
blurRadius: 32,
offset: const Offset(0, 12),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SlideTransition(
position: _arrowSlide,
child: Container(
width: 88,
height: 88,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.18),
shape: BoxShape.circle,
),
child: Icon(
isSuccess
? Icons.arrow_downward_rounded
: Icons.warning_amber_rounded,
size: isSuccess ? 52 : 46,
color: Colors.white,
),
),
),
const SizedBox(height: 20),
Text(
isSuccess ? '¡Pase válido!' : 'No se pudo validar',
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
if (!isSuccess && (_message?.isNotEmpty ?? false)) ...[
const SizedBox(height: 10),
Text(
_message!,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
height: 1.4,
color: Colors.white.withValues(alpha: 0.92),
),
),
],
if (isSuccess && _passCode != null) ...[
const SizedBox(height: 20),
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.18),
borderRadius: BorderRadius.circular(16),
),
child: Column(
children: [
_detailRow('Nombre', _passCode!.name),
const SizedBox(height: 8),
_detailRow('Código', _passCode!.code),
],
),
),
],
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: _scanAgain,
icon: const Icon(Icons.qr_code_scanner_rounded),
label: const Text('Escanear otro'),
style: FilledButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: accentDark,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
),
),
),
],
),
),
),
);
}
Widget _detailRow(String label, String value) {
return Row(
children: [
Text(
'$label: ',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 14,
),
),
Expanded(
child: Text(
value,
textAlign: TextAlign.end,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
),
],
);
}
Widget _buildHardwareScannerView() {
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
AppTheme.backgroundDark,
Color(0xFF0D1B2A),
Color(0xFF12182B),
],
),
),
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 36),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 120,
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28),
color: AppTheme.primary.withValues(alpha: 0.12),
border: Border.all(
color: AppTheme.primary.withValues(alpha: 0.35),
),
),
child: const Icon(
Icons.barcode_reader,
size: 56,
color: AppTheme.primary,
),
),
const SizedBox(height: 28),
Text(
'Escáner Honeywell',
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 12),
Text(
'Presiona el botón lateral del EDA51 para leer el código QR del pase.',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Colors.white.withValues(alpha: 0.6),
height: 1.5,
),
),
const SizedBox(height: 20),
Container(
padding:
const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.white.withValues(alpha: 0.08),
),
),
child: Text(
'Sensor dedicado · Honeywell ScanPal EDA51',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.45),
fontSize: 12,
),
),
),
],
),
),
),
);
}
Widget _buildHint() {
final message = _inputMode == _ScannerInput.hardware
? 'Presiona el botón lateral para escanear'
: 'Apunta la cámara al código QR del pase';
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
message,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.65),
fontSize: 14,
),
),
);
}
}
class _ScannerOverlayPainter extends CustomPainter {
_ScannerOverlayPainter({
required this.scanRect,
required this.scanLineProgress,
});
final Rect scanRect;
final double scanLineProgress;
static const double _cornerLength = 36;
static const double _cornerStroke = 4;
@override
void paint(Canvas canvas, Size size) {
final cutout = RRect.fromRectAndRadius(
scanRect,
const Radius.circular(_scanWindowRadius),
);
final background = Path()..addRect(Offset.zero & size);
final hole = Path()..addRRect(cutout);
final overlay = Path.combine(PathOperation.difference, background, hole);
canvas.drawPath(
overlay,
Paint()..color = Colors.black.withValues(alpha: 0.55),
);
final borderPaint = Paint()
..color = AppTheme.primary.withValues(alpha: 0.35)
..style = PaintingStyle.stroke
..strokeWidth = 1.5;
canvas.drawRRect(cutout, borderPaint);
final cornerPaint = Paint()
..color = AppTheme.primary
..style = PaintingStyle.stroke
..strokeWidth = _cornerStroke
..strokeCap = StrokeCap.round;
_drawCorners(canvas, scanRect, cornerPaint);
final lineY = scanRect.top +
_scanWindowRadius +
(scanRect.height - _scanWindowRadius * 2) * scanLineProgress;
final linePaint = Paint()
..shader = LinearGradient(
colors: [
AppTheme.primary.withValues(alpha: 0),
AppTheme.primary.withValues(alpha: 0.85),
AppTheme.primary.withValues(alpha: 0),
],
stops: const [0, 0.5, 1],
).createShader(
Rect.fromLTWH(scanRect.left + 16, lineY - 1, scanRect.width - 32, 2),
)
..strokeWidth = 2
..strokeCap = StrokeCap.round;
canvas.drawLine(
Offset(scanRect.left + 16, lineY),
Offset(scanRect.right - 16, lineY),
linePaint,
);
}
void _drawCorners(Canvas canvas, Rect rect, Paint paint) {
const r = _scanWindowRadius;
const len = _cornerLength;
canvas.drawLine(
Offset(rect.left + r, rect.top),
Offset(rect.left + r + len, rect.top),
paint,
);
canvas.drawLine(
Offset(rect.left, rect.top + r),
Offset(rect.left, rect.top + r + len),
paint,
);
canvas.drawLine(
Offset(rect.right - r - len, rect.top),
Offset(rect.right - r, rect.top),
paint,
);
canvas.drawLine(
Offset(rect.right, rect.top + r),
Offset(rect.right, rect.top + r + len),
paint,
);
canvas.drawLine(
Offset(rect.left + r, rect.bottom),
Offset(rect.left + r + len, rect.bottom),
paint,
);
canvas.drawLine(
Offset(rect.left, rect.bottom - r - len),
Offset(rect.left, rect.bottom - r),
paint,
);
canvas.drawLine(
Offset(rect.right - r - len, rect.bottom),
Offset(rect.right - r, rect.bottom),
paint,
);
canvas.drawLine(
Offset(rect.right, rect.bottom - r - len),
Offset(rect.right, rect.bottom - r),
paint,
);
}
@override
bool shouldRepaint(covariant _ScannerOverlayPainter oldDelegate) {
return oldDelegate.scanRect != scanRect ||
oldDelegate.scanLineProgress != scanLineProgress;
}
}