This commit is contained in:
2025-09-16 23:14:35 +07:00
parent be2ad0a8fd
commit 9ebe7c2919
55 changed files with 5953 additions and 893 deletions

View File

@@ -0,0 +1,344 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../providers/scanner_provider.dart';
/// Widget that provides barcode scanning functionality using device camera
class BarcodeScannerWidget extends ConsumerStatefulWidget {
const BarcodeScannerWidget({super.key});
@override
ConsumerState<BarcodeScannerWidget> createState() => _BarcodeScannerWidgetState();
}
class _BarcodeScannerWidgetState extends ConsumerState<BarcodeScannerWidget>
with WidgetsBindingObserver {
late MobileScannerController _controller;
bool _isStarted = false;
String? _lastScannedCode;
DateTime? _lastScanTime;
bool _isTorchOn = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_controller = MobileScannerController(
formats: [
BarcodeFormat.code128,
],
facing: CameraFacing.back,
torchEnabled: false,
);
_startScanner();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.paused:
_stopScanner();
break;
case AppLifecycleState.resumed:
_startScanner();
break;
case AppLifecycleState.detached:
case AppLifecycleState.inactive:
case AppLifecycleState.hidden:
break;
}
}
Future<void> _startScanner() async {
if (!_isStarted && mounted) {
try {
await _controller.start();
setState(() {
_isStarted = true;
});
} catch (e) {
debugPrint('Failed to start scanner: $e');
}
}
}
Future<void> _stopScanner() async {
if (_isStarted) {
try {
await _controller.stop();
setState(() {
_isStarted = false;
});
} catch (e) {
debugPrint('Failed to stop scanner: $e');
}
}
}
void _onBarcodeDetected(BarcodeCapture capture) {
final List<Barcode> barcodes = capture.barcodes;
if (barcodes.isNotEmpty) {
final barcode = barcodes.first;
final code = barcode.rawValue;
if (code != null && code.isNotEmpty) {
// Prevent duplicate scans within 2 seconds
final now = DateTime.now();
if (_lastScannedCode == code &&
_lastScanTime != null &&
now.difference(_lastScanTime!).inSeconds < 2) {
return;
}
_lastScannedCode = code;
_lastScanTime = now;
// Update scanner provider with new barcode
ref.read(scannerProvider.notifier).updateBarcode(code);
// Provide haptic feedback
_provideHapticFeedback();
}
}
}
void _provideHapticFeedback() {
// Haptic feedback is handled by the system
// You can add custom vibration here if needed
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(0),
),
child: Stack(
children: [
// Camera View
ClipRRect(
borderRadius: BorderRadius.circular(0),
child: MobileScanner(
controller: _controller,
onDetect: _onBarcodeDetected,
),
),
// Overlay with scanner frame
_buildScannerOverlay(context),
// Control buttons
_buildControlButtons(context),
],
),
);
}
/// Build scanner overlay with frame and guidance
Widget _buildScannerOverlay(BuildContext context) {
return Container(
decoration: const BoxDecoration(
color: Colors.transparent,
),
child: Stack(
children: [
// Dark overlay with cutout
Container(
color: Colors.black.withOpacity(0.5),
child: Center(
child: Container(
width: 250,
height: 150,
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary,
width: 2,
),
borderRadius: BorderRadius.circular(12),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.transparent,
),
),
),
),
),
// Instructions
Positioned(
bottom: 60,
left: 0,
right: 0,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
child: Text(
'Position barcode within the frame',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.white,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
),
),
],
),
);
}
/// Build control buttons (torch, camera switch)
Widget _buildControlButtons(BuildContext context) {
return Positioned(
top: 16,
right: 16,
child: Column(
children: [
// Torch Toggle
Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.6),
shape: BoxShape.circle,
),
child: IconButton(
icon: Icon(
_isTorchOn ? Icons.flash_on : Icons.flash_off,
color: Colors.white,
),
onPressed: _toggleTorch,
),
),
const SizedBox(height: 12),
// Camera Switch
Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.6),
shape: BoxShape.circle,
),
child: IconButton(
icon: const Icon(
Icons.cameraswitch,
color: Colors.white,
),
onPressed: _switchCamera,
),
),
],
),
);
}
/// Build error widget when camera fails
Widget _buildErrorWidget(MobileScannerException error) {
return Container(
color: Colors.black,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.camera_alt_outlined,
size: 64,
color: Theme.of(context).colorScheme.error,
),
const SizedBox(height: 16),
Text(
'Camera Error',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Colors.white,
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
_getErrorMessage(error),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.white70,
),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _restartScanner,
child: const Text('Retry'),
),
],
),
),
);
}
/// Build placeholder while camera is loading
Widget _buildPlaceholderWidget() {
return Container(
color: Colors.black,
child: const Center(
child: CircularProgressIndicator(
color: Colors.white,
),
),
);
}
/// Get user-friendly error message
String _getErrorMessage(MobileScannerException error) {
switch (error.errorCode) {
case MobileScannerErrorCode.permissionDenied:
return 'Camera permission is required to scan barcodes. Please enable camera access in settings.';
case MobileScannerErrorCode.unsupported:
return 'Your device does not support barcode scanning.';
default:
return 'Unable to access camera. Please check your device settings and try again.';
}
}
/// Toggle torch/flashlight
void _toggleTorch() async {
try {
await _controller.toggleTorch();
setState(() {
_isTorchOn = !_isTorchOn;
});
} catch (e) {
debugPrint('Failed to toggle torch: $e');
}
}
/// Switch between front and back camera
void _switchCamera() async {
try {
await _controller.switchCamera();
} catch (e) {
debugPrint('Failed to switch camera: $e');
}
}
/// Restart scanner after error
void _restartScanner() async {
try {
await _controller.stop();
await _controller.start();
setState(() {
_isStarted = true;
});
} catch (e) {
debugPrint('Failed to restart scanner: $e');
}
}
}

View File

@@ -0,0 +1,236 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../data/models/scan_item.dart';
/// Widget to display a scrollable list of scan history items
class ScanHistoryList extends StatelessWidget {
final List<ScanItem> history;
final Function(ScanItem)? onItemTap;
final Function(ScanItem)? onItemLongPress;
final bool showTimestamp;
const ScanHistoryList({
required this.history,
this.onItemTap,
this.onItemLongPress,
this.showTimestamp = true,
super.key,
});
@override
Widget build(BuildContext context) {
if (history.isEmpty) {
return _buildEmptyState(context);
}
return ListView.builder(
itemCount: history.length,
padding: const EdgeInsets.only(top: 8),
itemBuilder: (context, index) {
final scanItem = history[index];
return _buildHistoryItem(context, scanItem, index);
},
);
}
/// Build individual history item
Widget _buildHistoryItem(BuildContext context, ScanItem scanItem, int index) {
final hasData = scanItem.field1.isNotEmpty ||
scanItem.field2.isNotEmpty ||
scanItem.field3.isNotEmpty ||
scanItem.field4.isNotEmpty;
return Container(
margin: const EdgeInsets.only(bottom: 8),
child: Material(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(12),
elevation: 1,
child: InkWell(
onTap: onItemTap != null ? () => onItemTap!(scanItem) : null,
onLongPress: onItemLongPress != null ? () => onItemLongPress!(scanItem) : null,
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
width: 1,
),
),
child: Row(
children: [
// Icon indicating scan status
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: hasData
? Colors.green.withOpacity(0.1)
: Theme.of(context).colorScheme.primary.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
hasData ? Icons.check_circle : Icons.qr_code,
size: 20,
color: hasData
? Colors.green
: Theme.of(context).colorScheme.primary,
),
),
const SizedBox(width: 12),
// Barcode and details
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Barcode
Text(
scanItem.barcode,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontFamily: 'monospace',
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
// Status and timestamp
Row(
children: [
// Status indicator
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 2,
),
decoration: BoxDecoration(
color: hasData
? Colors.green.withOpacity(0.2)
: Theme.of(context).colorScheme.surfaceVariant,
borderRadius: BorderRadius.circular(12),
),
child: Text(
hasData ? 'Saved' : 'Scanned',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: hasData
? Colors.green.shade700
: Theme.of(context).colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w500,
),
),
),
if (showTimestamp) ...[
const SizedBox(width: 8),
Expanded(
child: Text(
_formatTimestamp(scanItem.timestamp),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
],
),
// Data preview (if available)
if (hasData) ...[
const SizedBox(height: 4),
Text(
_buildDataPreview(scanItem),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
),
),
// Chevron icon
if (onItemTap != null)
Icon(
Icons.chevron_right,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
],
),
),
),
),
);
}
/// Build empty state when no history is available
Widget _buildEmptyState(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.history,
size: 64,
color: Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.6),
),
const SizedBox(height: 16),
Text(
'No scan history',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Text(
'Scanned barcodes will appear here',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
],
),
);
}
/// Format timestamp for display
String _formatTimestamp(DateTime timestamp) {
final now = DateTime.now();
final difference = now.difference(timestamp);
if (difference.inDays > 0) {
return DateFormat('MMM dd, yyyy').format(timestamp);
} else if (difference.inHours > 0) {
return '${difference.inHours}h ago';
} else if (difference.inMinutes > 0) {
return '${difference.inMinutes}m ago';
} else {
return 'Just now';
}
}
/// Build preview of saved data
String _buildDataPreview(ScanItem scanItem) {
final fields = [
scanItem.field1,
scanItem.field2,
scanItem.field3,
scanItem.field4,
].where((field) => field.isNotEmpty).toList();
if (fields.isEmpty) {
return 'No data saved';
}
return fields.join('');
}
}

View File

@@ -0,0 +1,240 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Widget to display the most recent scan result with tap to edit functionality
class ScanResultDisplay extends StatelessWidget {
final String? barcode;
final VoidCallback? onTap;
final VoidCallback? onCopy;
const ScanResultDisplay({
required this.barcode,
this.onTap,
this.onCopy,
super.key,
});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceVariant,
border: Border(
top: BorderSide(
color: Theme.of(context).dividerColor,
width: 1,
),
bottom: BorderSide(
color: Theme.of(context).dividerColor,
width: 1,
),
),
),
child: barcode != null ? _buildScannedResult(context) : _buildEmptyState(context),
);
}
/// Build widget when barcode is scanned
Widget _buildScannedResult(BuildContext context) {
return Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
width: 1,
),
),
child: Row(
children: [
// Barcode icon
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
borderRadius: BorderRadius.circular(6),
),
child: Icon(
Icons.qr_code,
size: 24,
color: Theme.of(context).colorScheme.primary,
),
),
const SizedBox(width: 12),
// Barcode text and label
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Last Scanned',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(
barcode!,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontFamily: 'monospace',
fontWeight: FontWeight.bold,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (onTap != null) ...[
const SizedBox(height: 4),
Text(
'Tap to edit',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w500,
),
),
],
],
),
),
// Action buttons
Row(
mainAxisSize: MainAxisSize.min,
children: [
// Copy button
IconButton(
icon: Icon(
Icons.copy,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
onPressed: () => _copyToClipboard(context),
tooltip: 'Copy to clipboard',
visualDensity: VisualDensity.compact,
),
// Edit button (if tap is enabled)
if (onTap != null)
Icon(
Icons.arrow_forward_ios,
size: 16,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
],
),
],
),
),
),
);
}
/// Build empty state when no barcode is scanned
Widget _buildEmptyState(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Placeholder icon
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.1),
borderRadius: BorderRadius.circular(6),
),
child: Icon(
Icons.qr_code_scanner,
size: 24,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(width: 12),
// Placeholder text
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'No barcode scanned',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(
'Point camera at barcode to scan',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
),
// Scan animation (optional visual feedback)
_buildScanAnimation(context),
],
),
);
}
/// Build scanning animation indicator
Widget _buildScanAnimation(BuildContext context) {
return TweenAnimationBuilder<double>(
duration: const Duration(seconds: 2),
tween: Tween(begin: 0.0, end: 1.0),
builder: (context, value, child) {
return Opacity(
opacity: (1.0 - value).clamp(0.3, 1.0),
child: Container(
width: 4,
height: 24,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(2),
),
),
);
},
onEnd: () {
// Restart animation (this creates a continuous effect)
},
);
}
/// Copy barcode to clipboard
void _copyToClipboard(BuildContext context) {
if (barcode != null) {
Clipboard.setData(ClipboardData(text: barcode!));
// Show feedback
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Copied "$barcode" to clipboard'),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
action: SnackBarAction(
label: 'OK',
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
),
);
}
// Call custom onCopy callback if provided
onCopy?.call();
}
}