docs: reordenar documentación — agents.md como mapa corto de 7 secciones
- agents.md: reglas de trabajo, reglas duras, cadena ideas→objetivos→tareas, estado actual corto e índice con «cuándo leerlo» - Regla fundamental para equipos Windows (siax-asus) en cabecera - Stack, módulos y arquitectura → proyecto_estructura.md - Antecedentes, justificaciones e historial con lo más nuevo arriba → proyecto_memoria.md - Trazabilidad ideas→objetivos→tareas en ideas.md, objetivos.md y tareas.md - chats.md: registro obligatorio de mensajes leídos de sigma-robot - .gitignore: seguimiento de .agente/ manteniendo infraestructura.md dinámico ignorado
This commit is contained in:
@@ -0,0 +1,371 @@
|
||||
# Scanner de Cámara — QR y Códigos de Barras
|
||||
|
||||
> Documentación técnica reutilizable · Agente Ventas SIGMAC · 2026-06-14
|
||||
|
||||
---
|
||||
|
||||
## 1. Librería elegida: `mobile_scanner`
|
||||
|
||||
```yaml
|
||||
# pubspec.yaml
|
||||
dependencies:
|
||||
mobile_scanner: ^0.2.0 # versión resuelta con Flutter 2.11 / Dart 2.17-beta
|
||||
```
|
||||
|
||||
### Por qué `mobile_scanner` y no otras
|
||||
|
||||
| Librería | Pros | Contras | Veredicto |
|
||||
|---|---|---|---|
|
||||
| **mobile_scanner** | API limpia, activa, soporta QR + 1D, flash/flip builtin | No soporta Linux/Windows | ✅ Elegida |
|
||||
| `qr_code_scanner` | Muy usada, ZXing | Abandonada (sin mantenimiento desde 2022) | ❌ |
|
||||
| `flutter_barcode_scanner` | Simple | Solo Android/iOS, pobre UX | ❌ |
|
||||
| `scan` | Mínima, ligera | Sin flutter 2.x activo, sin control de cámara | ❌ |
|
||||
| `camera` + `google_ml_kit` | Máximo control | Muy complejo, pesado, requiere Firebase config | ❌ para scanner simple |
|
||||
|
||||
**Razón principal:** `mobile_scanner` es el sucesor mantenido de `qr_code_scanner`,
|
||||
usa las APIs nativas de la plataforma (MLKit en Android, AVFoundation en iOS),
|
||||
y tiene una API de widget simple que no requiere permisos manuales adicionales
|
||||
más allá del `CAMERA` en AndroidManifest.
|
||||
|
||||
### Nota de versión
|
||||
|
||||
Con Flutter 2.11 / Dart `>=2.17.0-69.2.beta <3.0.0`, `pub get` resuelve
|
||||
`mobile_scanner 0.2.0` (la más reciente compatible con ese SDK constraint).
|
||||
Con Flutter 3.x se puede usar `mobile_scanner ^3.x` o superior con APIs mejoradas.
|
||||
|
||||
---
|
||||
|
||||
## 2. Plataformas soportadas
|
||||
|
||||
| Plataforma | Soporte real | Estrategia |
|
||||
|---|---|---|
|
||||
| Android | ✅ Cámara real | `MobileScanner` widget |
|
||||
| iOS | ✅ Cámara real | `MobileScanner` widget |
|
||||
| macOS | ✅ Cámara real | `MobileScanner` widget |
|
||||
| Web | ⚠️ Parcial (v0.2 limitado) | `MobileScanner` widget |
|
||||
| Linux | ❌ Sin soporte | Fallback: diálogo input manual |
|
||||
| Windows | ❌ Sin soporte | Fallback: diálogo input manual |
|
||||
|
||||
---
|
||||
|
||||
## 3. Permisos requeridos
|
||||
|
||||
### Android — `android/app/src/main/AndroidManifest.xml`
|
||||
|
||||
```xml
|
||||
<uses-permission android:name="android.permission.CAMERA"/>
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false"/>
|
||||
```
|
||||
|
||||
`required="false"` permite instalar la app en dispositivos sin cámara;
|
||||
la función simplemente no aparece o muestra fallback.
|
||||
|
||||
### iOS — `ios/Runner/Info.plist`
|
||||
|
||||
```xml
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Necesitamos acceso a la cámara para escanear códigos QR y de barras.</string>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Arquitectura de la implementación
|
||||
|
||||
```
|
||||
lib/screens/scanner/
|
||||
├── scanner_screen.dart ← Pantalla full-screen con cámara
|
||||
└── scanner_helper.dart ← Función pública abrirScanner() + fallback Linux
|
||||
```
|
||||
|
||||
### Flujo de uso
|
||||
|
||||
```
|
||||
cualquier pantalla
|
||||
│
|
||||
└─ await abrirScanner(context, titulo: '...')
|
||||
│
|
||||
├── Android/iOS/macOS → push ScannerScreen → retorna String?
|
||||
│
|
||||
└── Linux/Windows → showDialog(input manual) → retorna String?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Código completo reutilizable
|
||||
|
||||
### 5.1 `scanner_helper.dart` — punto de entrada público
|
||||
|
||||
```dart
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'scanner_screen.dart';
|
||||
|
||||
/// Abre el scanner. Retorna el valor escaneado/ingresado, o null si se canceló.
|
||||
Future<String?> abrirScanner(BuildContext context, {String titulo = 'Escanear código'}) {
|
||||
if (!kIsWeb && (Platform.isLinux || Platform.isWindows)) {
|
||||
return _mostrarInputManual(context, titulo: titulo);
|
||||
}
|
||||
return Navigator.push<String>(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => ScannerScreen(titulo: titulo)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<String?> _mostrarInputManual(BuildContext context, {required String titulo}) {
|
||||
final ctrl = TextEditingController();
|
||||
return showDialog<String>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Row(children: [
|
||||
const Icon(Icons.qr_code, size: 22),
|
||||
const SizedBox(width: 8),
|
||||
Text(titulo, style: const TextStyle(fontSize: 16)),
|
||||
]),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
'Escaneo de cámara no disponible en escritorio.\nIngresa el código manualmente:',
|
||||
style: TextStyle(fontSize: 13, color: Colors.black54),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextField(
|
||||
controller: ctrl,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Código / SKU',
|
||||
prefixIcon: Icon(Icons.qr_code),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
onSubmitted: (v) {
|
||||
if (v.trim().isNotEmpty) Navigator.pop(ctx, v.trim());
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancelar')),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
final v = ctrl.text.trim();
|
||||
if (v.isNotEmpty) Navigator.pop(ctx, v);
|
||||
},
|
||||
child: const Text('Buscar'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 `scanner_screen.dart` — pantalla de cámara
|
||||
|
||||
```dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
|
||||
class ScannerScreen extends StatefulWidget {
|
||||
final String titulo;
|
||||
const ScannerScreen({Key? key, this.titulo = 'Escanear código'}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<ScannerScreen> createState() => _ScannerScreenState();
|
||||
}
|
||||
|
||||
class _ScannerScreenState extends State<ScannerScreen> {
|
||||
final _controller = MobileScannerController();
|
||||
bool _scanned = false; // evita múltiples pops por el mismo código
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onDetect(Barcode barcode, MobileScannerArguments? args) {
|
||||
if (_scanned || barcode.rawValue == null || barcode.rawValue!.isEmpty) return;
|
||||
_scanned = true;
|
||||
Navigator.pop(context, barcode.rawValue);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
title: Text(widget.titulo),
|
||||
actions: [
|
||||
// Linterna
|
||||
ValueListenableBuilder<TorchState>(
|
||||
valueListenable: _controller.torchState,
|
||||
builder: (_, state, __) => IconButton(
|
||||
icon: Icon(
|
||||
state == TorchState.on ? Icons.flash_on : Icons.flash_off,
|
||||
color: state == TorchState.on ? Colors.yellow : Colors.white,
|
||||
),
|
||||
onPressed: _controller.toggleTorch,
|
||||
),
|
||||
),
|
||||
// Cambiar cámara (front/back)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.cameraswitch, color: Colors.white),
|
||||
onPressed: _controller.switchCamera,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
MobileScanner(
|
||||
controller: _controller,
|
||||
fit: BoxFit.cover,
|
||||
onDetect: _onDetect,
|
||||
),
|
||||
// Overlay visual con recuadro de escaneo
|
||||
CustomPaint(
|
||||
painter: _ScanOverlayPainter(),
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
Positioned(
|
||||
left: 0, right: 0, bottom: 56,
|
||||
child: Column(children: const [
|
||||
Icon(Icons.qr_code_scanner, color: Colors.white38, size: 28),
|
||||
SizedBox(height: 10),
|
||||
Text(
|
||||
'Apunta al código QR o código de barras',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.white70, fontSize: 13),
|
||||
),
|
||||
]),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dibuja el overlay oscuro con un "agujero" transparente en el centro
|
||||
/// y brackets en las esquinas del recuadro de escaneo.
|
||||
class _ScanOverlayPainter extends CustomPainter {
|
||||
final Color bracketColor;
|
||||
_ScanOverlayPainter({this.bracketColor = const Color(0xFF1E40AF)});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final frameSize = size.width * 0.72;
|
||||
final left = (size.width - frameSize) / 2;
|
||||
final top = (size.height - frameSize) / 2 - 40;
|
||||
final frame = Rect.fromLTWH(left, top, frameSize, frameSize);
|
||||
|
||||
// Overlay semitransparente con agujero
|
||||
final overlay = Paint()..color = Colors.black.withOpacity(0.55);
|
||||
final outer = Path()..addRect(Rect.fromLTWH(0, 0, size.width, size.height));
|
||||
final inner = Path()..addRRect(RRect.fromRectAndRadius(frame, const Radius.circular(10)));
|
||||
canvas.drawPath(Path.combine(PathOperation.difference, outer, inner), overlay);
|
||||
|
||||
// Brackets en esquinas
|
||||
final bracket = Paint()
|
||||
..color = bracketColor
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 3.5
|
||||
..strokeCap = StrokeCap.round;
|
||||
|
||||
const cl = 22.0;
|
||||
final l = frame.left; final t = frame.top;
|
||||
final r = frame.right; final b = frame.bottom;
|
||||
|
||||
canvas.drawLine(Offset(l, t + cl), Offset(l, t), bracket);
|
||||
canvas.drawLine(Offset(l, t), Offset(l + cl, t), bracket);
|
||||
canvas.drawLine(Offset(r - cl, t), Offset(r, t), bracket);
|
||||
canvas.drawLine(Offset(r, t), Offset(r, t + cl), bracket);
|
||||
canvas.drawLine(Offset(l, b - cl), Offset(l, b), bracket);
|
||||
canvas.drawLine(Offset(l, b), Offset(l + cl, b), bracket);
|
||||
canvas.drawLine(Offset(r - cl, b), Offset(r, b), bracket);
|
||||
canvas.drawLine(Offset(r, b), Offset(r, b - cl), bracket);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_) => false;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Cómo usar en otra app Flutter
|
||||
|
||||
### Paso 1 — Agregar dependencia
|
||||
|
||||
```yaml
|
||||
# pubspec.yaml
|
||||
dependencies:
|
||||
mobile_scanner: ^0.2.0 # Flutter 2.x
|
||||
# mobile_scanner: ^3.0.0 # Flutter 3.x
|
||||
```
|
||||
|
||||
### Paso 2 — Copiar los dos archivos
|
||||
|
||||
```
|
||||
lib/screens/scanner/scanner_screen.dart
|
||||
lib/screens/scanner/scanner_helper.dart
|
||||
```
|
||||
|
||||
Si la app tiene un tema personalizado, reemplaza el color hardcodeado
|
||||
`Color(0xFF1E40AF)` en `_ScanOverlayPainter` por `Theme.of(context).primaryColor`
|
||||
o pásalo como parámetro `bracketColor`.
|
||||
|
||||
### Paso 3 — Permisos
|
||||
|
||||
- Android: agregar `<uses-permission android:name="android.permission.CAMERA"/>` al AndroidManifest
|
||||
- iOS: agregar `NSCameraUsageDescription` al Info.plist
|
||||
|
||||
### Paso 4 — Llamar desde cualquier widget
|
||||
|
||||
```dart
|
||||
import '../scanner/scanner_helper.dart';
|
||||
|
||||
// Ejemplo: al pulsar un botón
|
||||
onPressed: () async {
|
||||
final codigo = await abrirScanner(context, titulo: 'Escanear producto');
|
||||
if (codigo != null) {
|
||||
// usar codigo...
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
### Valores de retorno
|
||||
|
||||
| Resultado | Significado |
|
||||
|---|---|
|
||||
| `String` no vacío | Código escaneado o ingresado manualmente |
|
||||
| `null` | Usuario canceló |
|
||||
|
||||
---
|
||||
|
||||
## 7. Tipos de código detectados (mobile_scanner 0.2.0)
|
||||
|
||||
Por defecto detecta todos los formatos. Para restringir:
|
||||
|
||||
```dart
|
||||
MobileScannerController(
|
||||
formats: [BarcodeFormat.qrCode], // solo QR
|
||||
// formats: [BarcodeFormat.ean13, BarcodeFormat.code128], // solo barcodes
|
||||
)
|
||||
```
|
||||
|
||||
Formatos comunes disponibles: `qrCode`, `ean8`, `ean13`, `code39`, `code128`,
|
||||
`pdf417`, `aztec`, `dataMatrix`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Consideraciones de seguridad
|
||||
|
||||
- No confiar ciegamente en el valor escaneado — validar contra la base de datos local antes de actuar.
|
||||
- Los QR pueden contener URLs maliciosas si la app permite escanear QR genéricos. Si solo se usan SKUs internos, validar que el formato sea el esperado (ej. regex `^[A-Z]{3}-\d{4}$`).
|
||||
- No almacenar el valor crudo del QR sin sanitizar si se usa como parámetro SQL.
|
||||
|
||||
---
|
||||
|
||||
*Archivo generado por Claude Code · Agente Ventas SIGMAC · 2026-06-14*
|
||||
Reference in New Issue
Block a user