clean design e bloc
This commit is contained in:
1 parent
b2cf67fdca
commit
6935020cac
51 files changed
+3716
-1780
No files matched your search
@@ -21,11 +21,15 @@ barcode_reader_pc/
|
||||
└── app/ # App Mobile Flutter (Android & iOS)
|
||||
├── lib/
|
||||
│ ├── main.dart
|
||||
│ ├── models/ # ScanRecord, ServerConnection
|
||||
│ ├── services/ # WebSocket, UDP Discovery, Feedback aptico/sonoro, Storage
|
||||
│ ├── screens/ # ScannerScreen, ConnectScreen, HistoryScreen, SettingsScreen
|
||||
│ └── widgets/ # Mirino laser personalizzato ScannerOverlay
|
||||
└── pubspec.yaml # Dipendenze Flutter (mobile_scanner, web_socket_channel, ecc.)
|
||||
│ ├── core/ # Temi (dark/light clean design), costanti, servizi feedback
|
||||
│ │ ├── constants/
|
||||
│ │ ├── services/
|
||||
│ │ └── theme/
|
||||
│ └── features/ # Architettura Clean a Feature con BLoC / Cubit
|
||||
│ ├── connection/ # Data, Domain, Presentation (ConnectionCubit, DiscoveryCubit, ConnectScreen)
|
||||
│ ├── scanner/ # Data, Domain, Presentation (ScannerCubit, HistoryCubit, ScannerScreen, Overlay)
|
||||
│ └── settings/ # Data, Domain, Presentation (SettingsCubit, SettingsScreen)
|
||||
└── pubspec.yaml # Dipendenze Flutter (flutter_bloc, equatable, mobile_scanner, ecc.)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
class AppConstants {
|
||||
AppConstants._();
|
||||
|
||||
static const String appName = 'Catelli Barcode Reader';
|
||||
static const String appVersion = '1.0.0';
|
||||
static const String organization = 'Catelli Srl';
|
||||
|
||||
// Network defaults
|
||||
static const int defaultPort = 8765;
|
||||
static const int defaultUdpDiscoveryPort = 8766;
|
||||
static const String udpDiscoveryMessage = 'DISCOVER_BARCODE_SERVER';
|
||||
|
||||
// Storage keys
|
||||
static const String keyIp = 'server_ip';
|
||||
static const String keyPort = 'server_port';
|
||||
static const String keyPin = 'server_pin';
|
||||
static const String keyServerName = 'server_name';
|
||||
static const String keySuffix = 'server_suffix';
|
||||
static const String keyContinuous = 'continuous_mode';
|
||||
static const String keyVibrate = 'vibrate_enabled';
|
||||
static const String keySound = 'sound_enabled';
|
||||
static const String keyHistory = 'scan_history';
|
||||
|
||||
// Suffix options
|
||||
static const String suffixEnter = 'enter';
|
||||
static const String suffixTab = 'tab';
|
||||
static const String suffixNone = 'none';
|
||||
}
|
||||
|
||||
+12
-3
@@ -1,7 +1,9 @@
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class FeedbackService {
|
||||
static Future<void> triggerFeedback({bool sound = true, bool vibrate = true}) async {
|
||||
const FeedbackService();
|
||||
|
||||
Future<void> triggerScanFeedback({required bool sound, required bool vibrate}) async {
|
||||
try {
|
||||
if (vibrate) {
|
||||
await HapticFeedback.mediumImpact();
|
||||
@@ -12,15 +14,22 @@ class FeedbackService {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
static Future<void> triggerSuccess() async {
|
||||
Future<void> triggerSuccess() async {
|
||||
try {
|
||||
await HapticFeedback.heavyImpact();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
static Future<void> triggerError() async {
|
||||
Future<void> triggerError() async {
|
||||
try {
|
||||
await HapticFeedback.vibrate();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> triggerSelection() async {
|
||||
try {
|
||||
await HapticFeedback.selectionClick();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppTheme {
|
||||
AppTheme._();
|
||||
|
||||
// Primary brand palette - High-tech Cyan & Industrial Slate
|
||||
static const Color primary = Color(0xFF0EA5E9); // Bright Sky / Cyan
|
||||
static const Color primaryDark = Color(0xFF0284C7);
|
||||
static const Color secondary = Color(0xFF38BDF8);
|
||||
static const Color accent = Color(0xFF06B6D4);
|
||||
|
||||
// Status Colors
|
||||
static const Color success = Color(0xFF10B981);
|
||||
static const Color warning = Color(0xFFF59E0B);
|
||||
static const Color error = Color(0xFFEF4444);
|
||||
|
||||
// Dark Palette (Default - High contrast for barcode scanning)
|
||||
static const Color darkBackground = Color(0xFF090D16);
|
||||
static const Color darkSurface = Color(0xFF0F172A);
|
||||
static const Color darkCard = Color(0xFF1E293B);
|
||||
static const Color darkBorder = Color(0xFF334155);
|
||||
static const Color darkTextPrimary = Color(0xFFF8FAFC);
|
||||
static const Color darkTextSecondary = Color(0xFF94A3B8);
|
||||
|
||||
// Light Palette
|
||||
static const Color lightBackground = Color(0xFFF8FAFC);
|
||||
static const Color lightSurface = Color(0xFFFFFFFF);
|
||||
static const Color lightCard = Color(0xFFFFFFFF);
|
||||
static const Color lightBorder = Color(0xFFE2E8F0);
|
||||
static const Color lightTextPrimary = Color(0xFF0F172A);
|
||||
static const Color lightTextSecondary = Color(0xFF64748B);
|
||||
|
||||
static ThemeData get darkTheme {
|
||||
return ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.dark,
|
||||
scaffoldBackgroundColor: darkBackground,
|
||||
colorScheme: const ColorScheme.dark(
|
||||
primary: primary,
|
||||
secondary: secondary,
|
||||
surface: darkSurface,
|
||||
error: error,
|
||||
onPrimary: Colors.white,
|
||||
onSecondary: Colors.white,
|
||||
onSurface: darkTextPrimary,
|
||||
onError: Colors.white,
|
||||
),
|
||||
appBarTheme: const AppBarTheme(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
centerTitle: false,
|
||||
scrolledUnderElevation: 0,
|
||||
titleTextStyle: TextStyle(
|
||||
color: darkTextPrimary,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: -0.3,
|
||||
),
|
||||
iconTheme: IconThemeData(color: darkTextPrimary),
|
||||
),
|
||||
cardTheme: CardThemeData(
|
||||
color: darkCard,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: const BorderSide(color: darkBorder, width: 1),
|
||||
),
|
||||
margin: EdgeInsets.zero,
|
||||
),
|
||||
dialogTheme: DialogThemeData(
|
||||
backgroundColor: darkSurface,
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
side: const BorderSide(color: darkBorder, width: 1),
|
||||
),
|
||||
),
|
||||
bottomSheetTheme: const BottomSheetThemeData(
|
||||
backgroundColor: darkSurface,
|
||||
modalBackgroundColor: darkSurface,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
|
||||
),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: darkCard,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: darkBorder),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: darkBorder),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: primary, width: 2),
|
||||
),
|
||||
errorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: error),
|
||||
),
|
||||
hintStyle: const TextStyle(color: darkTextSecondary, fontSize: 14),
|
||||
labelStyle: const TextStyle(color: darkTextSecondary, fontSize: 14),
|
||||
),
|
||||
elevatedButtonTheme: ElevatedButtonThemeData(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: primary,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
filledButtonTheme: FilledButtonThemeData(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: primary,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
outlinedButtonTheme: OutlinedButtonThemeData(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: primary,
|
||||
side: const BorderSide(color: darkBorder, width: 1.5),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
dividerTheme: const DividerThemeData(
|
||||
color: darkBorder,
|
||||
thickness: 1,
|
||||
space: 24,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static ThemeData get lightTheme {
|
||||
return ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.light,
|
||||
scaffoldBackgroundColor: lightBackground,
|
||||
colorScheme: const ColorScheme.light(
|
||||
primary: primaryDark,
|
||||
secondary: secondary,
|
||||
surface: lightSurface,
|
||||
error: error,
|
||||
onPrimary: Colors.white,
|
||||
onSecondary: Colors.white,
|
||||
onSurface: lightTextPrimary,
|
||||
onError: Colors.white,
|
||||
),
|
||||
appBarTheme: const AppBarTheme(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
centerTitle: false,
|
||||
scrolledUnderElevation: 0,
|
||||
titleTextStyle: TextStyle(
|
||||
color: lightTextPrimary,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: -0.3,
|
||||
),
|
||||
iconTheme: IconThemeData(color: lightTextPrimary),
|
||||
),
|
||||
cardTheme: CardThemeData(
|
||||
color: lightCard,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: const BorderSide(color: lightBorder, width: 1),
|
||||
),
|
||||
margin: EdgeInsets.zero,
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: const Color(0xFFF1F5F9),
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: lightBorder),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: lightBorder),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: primaryDark, width: 2),
|
||||
),
|
||||
hintStyle: const TextStyle(color: lightTextSecondary, fontSize: 14),
|
||||
),
|
||||
filledButtonTheme: FilledButtonThemeData(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: primaryDark,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
outlinedButtonTheme: OutlinedButtonThemeData(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: primaryDark,
|
||||
side: const BorderSide(color: lightBorder, width: 1.5),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
dividerTheme: const DividerThemeData(
|
||||
color: lightBorder,
|
||||
thickness: 1,
|
||||
space: 24,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../../core/constants/app_constants.dart';
|
||||
import '../../domain/entities/server_connection_info.dart';
|
||||
|
||||
class ConnectionLocalDataSource {
|
||||
final SharedPreferences _prefs;
|
||||
|
||||
ConnectionLocalDataSource(this._prefs);
|
||||
|
||||
ServerConnectionInfo loadConnectionInfo() {
|
||||
final ip = _prefs.getString(AppConstants.keyIp) ?? '';
|
||||
final port = _prefs.getInt(AppConstants.keyPort) ?? AppConstants.defaultPort;
|
||||
final pin = _prefs.getString(AppConstants.keyPin) ?? '';
|
||||
final serverName = _prefs.getString(AppConstants.keyServerName) ?? '';
|
||||
|
||||
return ServerConnectionInfo(
|
||||
ip: ip,
|
||||
port: port,
|
||||
pin: pin,
|
||||
serverName: serverName,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> saveConnectionInfo(ServerConnectionInfo info) async {
|
||||
await _prefs.setString(AppConstants.keyIp, info.ip);
|
||||
await _prefs.setInt(AppConstants.keyPort, info.port);
|
||||
await _prefs.setString(AppConstants.keyPin, info.pin);
|
||||
if (info.serverName.isNotEmpty) {
|
||||
await _prefs.setString(AppConstants.keyServerName, info.serverName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import '../../domain/entities/server_connection_info.dart';
|
||||
import '../../domain/repositories/connection_repository.dart';
|
||||
|
||||
class ConnectionRemoteDataSource {
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription? _channelSub;
|
||||
Timer? _pingTimer;
|
||||
|
||||
final StreamController<ConnectionStatus> _statusController =
|
||||
StreamController<ConnectionStatus>.broadcast();
|
||||
final StreamController<String> _messageController =
|
||||
StreamController<String>.broadcast();
|
||||
final StreamController<String> _serverNameController =
|
||||
StreamController<String>.broadcast();
|
||||
|
||||
ConnectionStatus _status = ConnectionStatus.disconnected;
|
||||
|
||||
Stream<ConnectionStatus> get statusStream => _statusController.stream;
|
||||
Stream<String> get messageStream => _messageController.stream;
|
||||
Stream<String> get serverNameStream => _serverNameController.stream;
|
||||
ConnectionStatus get currentStatus => _status;
|
||||
|
||||
Future<void> connect(ServerConnectionInfo info) async {
|
||||
_disconnectInternal();
|
||||
|
||||
_setStatus(ConnectionStatus.connecting, 'Connessione a ${info.ip}:${info.port} in corso...');
|
||||
|
||||
try {
|
||||
final wsUrl = Uri.parse('ws://${info.ip}:${info.port}/ws');
|
||||
_channel = WebSocketChannel.connect(wsUrl);
|
||||
|
||||
_channelSub = _channel!.stream.listen(
|
||||
(data) {
|
||||
_handleMessage(data);
|
||||
},
|
||||
onError: (err) {
|
||||
_setStatus(ConnectionStatus.error, 'Errore di connessione: $err');
|
||||
_disconnectInternal();
|
||||
},
|
||||
onDone: () {
|
||||
if (_status != ConnectionStatus.disconnected) {
|
||||
_setStatus(ConnectionStatus.disconnected, 'Connessione interrotta dal server');
|
||||
}
|
||||
_disconnectInternal();
|
||||
},
|
||||
cancelOnError: true,
|
||||
);
|
||||
|
||||
final deviceName = Platform.isAndroid
|
||||
? 'Android'
|
||||
: (Platform.isIOS ? 'iPhone' : 'Dispositivo Mobile');
|
||||
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'handshake',
|
||||
'device_name': deviceName,
|
||||
'pin': info.pin,
|
||||
}));
|
||||
|
||||
_setStatus(ConnectionStatus.connected, 'Connesso a ${info.displayName}');
|
||||
_startPingLoop();
|
||||
} catch (e) {
|
||||
_setStatus(ConnectionStatus.error, 'Impossibile connettersi: $e');
|
||||
_disconnectInternal();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleMessage(dynamic raw) {
|
||||
try {
|
||||
final json = jsonDecode(raw.toString()) as Map<String, dynamic>;
|
||||
final type = json['type'] as String?;
|
||||
|
||||
if (type == 'welcome') {
|
||||
final serverName = json['server_name'] as String?;
|
||||
if (serverName != null && serverName.isNotEmpty) {
|
||||
_serverNameController.add(serverName);
|
||||
_setStatus(ConnectionStatus.connected, 'Connesso a $serverName');
|
||||
}
|
||||
} else if (type == 'auth_error') {
|
||||
_setStatus(ConnectionStatus.error, 'PIN errato: autenticazione fallita');
|
||||
_disconnectInternal();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<bool> sendCode({
|
||||
required String code,
|
||||
required String suffix,
|
||||
required String pin,
|
||||
required String ip,
|
||||
required int port,
|
||||
}) async {
|
||||
final cleanCode = code.trim();
|
||||
if (cleanCode.isEmpty) return false;
|
||||
|
||||
// 1. Try WebSocket if connected
|
||||
if (_status == ConnectionStatus.connected && _channel != null) {
|
||||
try {
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'scan',
|
||||
'code': cleanCode,
|
||||
'suffix': suffix,
|
||||
'pin': pin,
|
||||
}));
|
||||
return true;
|
||||
} catch (_) {
|
||||
// Fallback to HTTP
|
||||
}
|
||||
}
|
||||
|
||||
// 2. HTTP Fallback
|
||||
if (ip.isNotEmpty) {
|
||||
try {
|
||||
final uri = Uri.parse('http://$ip:$port/api/type');
|
||||
final response = await http.post(
|
||||
uri,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'code': cleanCode,
|
||||
'suffix': suffix,
|
||||
'pin': pin,
|
||||
'source': Platform.isAndroid ? 'Android (HTTP)' : 'iOS (HTTP)',
|
||||
}),
|
||||
).timeout(const Duration(seconds: 2));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return true;
|
||||
}
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_setStatus(ConnectionStatus.disconnected, 'Disconnesso');
|
||||
_disconnectInternal();
|
||||
}
|
||||
|
||||
void _disconnectInternal() {
|
||||
_pingTimer?.cancel();
|
||||
_pingTimer = null;
|
||||
_channelSub?.cancel();
|
||||
_channelSub = null;
|
||||
try {
|
||||
_channel?.sink.close();
|
||||
} catch (_) {}
|
||||
_channel = null;
|
||||
}
|
||||
|
||||
void _setStatus(ConnectionStatus status, String message) {
|
||||
_status = status;
|
||||
_statusController.add(status);
|
||||
_messageController.add(message);
|
||||
}
|
||||
|
||||
void _startPingLoop() {
|
||||
_pingTimer?.cancel();
|
||||
_pingTimer = Timer.periodic(const Duration(seconds: 15), (_) {
|
||||
if (_status == ConnectionStatus.connected && _channel != null) {
|
||||
try {
|
||||
_channel!.sink.add(jsonEncode({'type': 'ping'}));
|
||||
} catch (_) {}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_disconnectInternal();
|
||||
_statusController.close();
|
||||
_messageController.close();
|
||||
_serverNameController.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import '../../../../core/constants/app_constants.dart';
|
||||
import '../../domain/entities/discovered_server.dart';
|
||||
|
||||
class UdpDiscoveryDataSource {
|
||||
const UdpDiscoveryDataSource();
|
||||
|
||||
Future<List<DiscoveredServer>> discover({
|
||||
Duration timeout = const Duration(seconds: 3),
|
||||
}) async {
|
||||
final Map<String, DiscoveredServer> found = {};
|
||||
RawDatagramSocket? socket;
|
||||
|
||||
try {
|
||||
socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
|
||||
socket.broadcastEnabled = true;
|
||||
|
||||
final data = utf8.encode(AppConstants.udpDiscoveryMessage);
|
||||
socket.send(
|
||||
data,
|
||||
InternetAddress('255.255.255.255'),
|
||||
AppConstants.defaultUdpDiscoveryPort,
|
||||
);
|
||||
|
||||
final completer = Completer<List<DiscoveredServer>>();
|
||||
|
||||
final sub = socket.listen((event) {
|
||||
if (event == RawSocketEvent.read) {
|
||||
final datagram = socket?.receive();
|
||||
if (datagram != null) {
|
||||
try {
|
||||
final text = utf8.decode(datagram.data);
|
||||
final json = jsonDecode(text) as Map<String, dynamic>;
|
||||
if (json['type'] == 'discover_response') {
|
||||
final server = DiscoveredServer.fromJson(json);
|
||||
if (server.ip.isNotEmpty) {
|
||||
found[server.ip] = server;
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Timer(timeout, () {
|
||||
if (!completer.isCompleted) {
|
||||
sub.cancel();
|
||||
socket?.close();
|
||||
completer.complete(found.values.toList());
|
||||
}
|
||||
});
|
||||
|
||||
return await completer.future;
|
||||
} catch (_) {
|
||||
socket?.close();
|
||||
return found.values.toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import 'dart:async';
|
||||
import '../../domain/entities/discovered_server.dart';
|
||||
import '../../domain/entities/server_connection_info.dart';
|
||||
import '../../domain/repositories/connection_repository.dart';
|
||||
import '../datasources/connection_local_datasource.dart';
|
||||
import '../datasources/connection_remote_datasource.dart';
|
||||
import '../datasources/udp_discovery_datasource.dart';
|
||||
|
||||
class ConnectionRepositoryImpl implements ConnectionRepository {
|
||||
final ConnectionLocalDataSource localDataSource;
|
||||
final ConnectionRemoteDataSource remoteDataSource;
|
||||
final UdpDiscoveryDataSource discoveryDataSource;
|
||||
|
||||
StreamSubscription? _serverNameSub;
|
||||
|
||||
ConnectionRepositoryImpl({
|
||||
required this.localDataSource,
|
||||
required this.remoteDataSource,
|
||||
required this.discoveryDataSource,
|
||||
}) {
|
||||
_serverNameSub = remoteDataSource.serverNameStream.listen((name) async {
|
||||
final current = localDataSource.loadConnectionInfo();
|
||||
if (current.serverName != name) {
|
||||
await localDataSource.saveConnectionInfo(current.copyWith(serverName: name));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<ConnectionStatus> get statusStream => remoteDataSource.statusStream;
|
||||
|
||||
@override
|
||||
Stream<String> get messageStream => remoteDataSource.messageStream;
|
||||
|
||||
@override
|
||||
ConnectionStatus get currentStatus => remoteDataSource.currentStatus;
|
||||
|
||||
@override
|
||||
Future<ServerConnectionInfo> loadSavedConnection() async {
|
||||
return localDataSource.loadConnectionInfo();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveConnection(ServerConnectionInfo info) async {
|
||||
await localDataSource.saveConnectionInfo(info);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> connect(ServerConnectionInfo info) async {
|
||||
await localDataSource.saveConnectionInfo(info);
|
||||
await remoteDataSource.connect(info);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> disconnect() async {
|
||||
remoteDataSource.disconnect();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> sendCode({
|
||||
required String code,
|
||||
required String suffix,
|
||||
required String pin,
|
||||
String? ip,
|
||||
int? port,
|
||||
}) async {
|
||||
final serverIp = ip ?? localDataSource.loadConnectionInfo().ip;
|
||||
final serverPort = port ?? localDataSource.loadConnectionInfo().port;
|
||||
|
||||
return await remoteDataSource.sendCode(
|
||||
code: code,
|
||||
suffix: suffix,
|
||||
pin: pin,
|
||||
ip: serverIp,
|
||||
port: serverPort,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<DiscoveredServer>> discoverServers({
|
||||
Duration timeout = const Duration(seconds: 3),
|
||||
}) async {
|
||||
return await discoveryDataSource.discover(timeout: timeout);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_serverNameSub?.cancel();
|
||||
remoteDataSource.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class DiscoveredServer extends Equatable {
|
||||
final String ip;
|
||||
final int port;
|
||||
final String serverName;
|
||||
final String wsUrl;
|
||||
final String httpUrl;
|
||||
final bool pinRequired;
|
||||
|
||||
const DiscoveredServer({
|
||||
required this.ip,
|
||||
required this.port,
|
||||
required this.serverName,
|
||||
required this.wsUrl,
|
||||
required this.httpUrl,
|
||||
required this.pinRequired,
|
||||
});
|
||||
|
||||
factory DiscoveredServer.fromJson(Map<String, dynamic> json) => DiscoveredServer(
|
||||
ip: json['ip'] as String? ?? '',
|
||||
port: json['port'] as int? ?? 8765,
|
||||
serverName: json['server_name'] as String? ?? 'PC Server',
|
||||
wsUrl: json['ws_url'] as String? ?? '',
|
||||
httpUrl: json['http_url'] as String? ?? '',
|
||||
pinRequired: json['pin_required'] as bool? ?? false,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [ip, port, serverName, wsUrl, httpUrl, pinRequired];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class ServerConnectionInfo extends Equatable {
|
||||
final String ip;
|
||||
final int port;
|
||||
final String pin;
|
||||
final String serverName;
|
||||
|
||||
const ServerConnectionInfo({
|
||||
this.ip = '',
|
||||
this.port = 8765,
|
||||
this.pin = '',
|
||||
this.serverName = '',
|
||||
});
|
||||
|
||||
String get displayName => serverName.isNotEmpty
|
||||
? serverName
|
||||
: (ip.isNotEmpty ? ip : 'Nessun PC');
|
||||
|
||||
bool get isConfigured => ip.isNotEmpty;
|
||||
|
||||
ServerConnectionInfo copyWith({
|
||||
String? ip,
|
||||
int? port,
|
||||
String? pin,
|
||||
String? serverName,
|
||||
}) {
|
||||
return ServerConnectionInfo(
|
||||
ip: ip ?? this.ip,
|
||||
port: port ?? this.port,
|
||||
pin: pin ?? this.pin,
|
||||
serverName: serverName ?? this.serverName,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [ip, port, pin, serverName];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import '../entities/discovered_server.dart';
|
||||
import '../entities/server_connection_info.dart';
|
||||
|
||||
enum ConnectionStatus {
|
||||
disconnected,
|
||||
connecting,
|
||||
connected,
|
||||
error,
|
||||
}
|
||||
|
||||
abstract class ConnectionRepository {
|
||||
Stream<ConnectionStatus> get statusStream;
|
||||
Stream<String> get messageStream;
|
||||
ConnectionStatus get currentStatus;
|
||||
|
||||
Future<ServerConnectionInfo> loadSavedConnection();
|
||||
Future<void> saveConnection(ServerConnectionInfo info);
|
||||
|
||||
Future<void> connect(ServerConnectionInfo info);
|
||||
Future<void> disconnect();
|
||||
|
||||
Future<bool> sendCode({
|
||||
required String code,
|
||||
required String suffix,
|
||||
required String pin,
|
||||
String? ip,
|
||||
int? port,
|
||||
});
|
||||
|
||||
Future<List<DiscoveredServer>> discoverServers({Duration timeout = const Duration(seconds: 3)});
|
||||
|
||||
void dispose();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../domain/entities/server_connection_info.dart';
|
||||
import '../../domain/repositories/connection_repository.dart';
|
||||
import 'connection_state.dart';
|
||||
|
||||
class ConnectionCubit extends Cubit<ServerConnectionState> {
|
||||
final ConnectionRepository _repository;
|
||||
StreamSubscription? _statusSubscription;
|
||||
StreamSubscription? _messageSubscription;
|
||||
Timer? _reconnectTimer;
|
||||
bool _userExplicitlyDisconnected = false;
|
||||
|
||||
ConnectionCubit(this._repository) : super(const ServerConnectionState()) {
|
||||
_statusSubscription = _repository.statusStream.listen(_onStatusChanged);
|
||||
_messageSubscription = _repository.messageStream.listen(_onMessageReceived);
|
||||
}
|
||||
|
||||
void _onStatusChanged(ConnectionStatus status) {
|
||||
emit(state.copyWith(status: status));
|
||||
if (status == ConnectionStatus.disconnected &&
|
||||
!_userExplicitlyDisconnected &&
|
||||
state.info.isConfigured) {
|
||||
_scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
void _onMessageReceived(String message) {
|
||||
emit(state.copyWith(statusMessage: message));
|
||||
}
|
||||
|
||||
void _scheduleReconnect() {
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = Timer(const Duration(seconds: 4), () {
|
||||
if (!_userExplicitlyDisconnected && !state.isConnected && state.info.isConfigured) {
|
||||
connect(state.info);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> initialize() async {
|
||||
final info = await _repository.loadSavedConnection();
|
||||
emit(state.copyWith(info: info));
|
||||
if (info.isConfigured) {
|
||||
await connect(info);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> connect(ServerConnectionInfo info) async {
|
||||
_userExplicitlyDisconnected = false;
|
||||
_reconnectTimer?.cancel();
|
||||
emit(state.copyWith(info: info, status: ConnectionStatus.connecting));
|
||||
await _repository.connect(info);
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
_userExplicitlyDisconnected = true;
|
||||
_reconnectTimer?.cancel();
|
||||
await _repository.disconnect();
|
||||
emit(state.copyWith(
|
||||
status: ConnectionStatus.disconnected,
|
||||
statusMessage: 'Disconnesso manualmente',
|
||||
));
|
||||
}
|
||||
|
||||
Future<bool> sendCode({
|
||||
required String code,
|
||||
required String suffix,
|
||||
}) async {
|
||||
return await _repository.sendCode(
|
||||
code: code,
|
||||
suffix: suffix,
|
||||
pin: state.info.pin,
|
||||
ip: state.info.ip,
|
||||
port: state.info.port,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_reconnectTimer?.cancel();
|
||||
_statusSubscription?.cancel();
|
||||
_messageSubscription?.cancel();
|
||||
_repository.dispose();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../domain/entities/server_connection_info.dart';
|
||||
import '../../domain/repositories/connection_repository.dart';
|
||||
|
||||
class ServerConnectionState extends Equatable {
|
||||
final ConnectionStatus status;
|
||||
final String statusMessage;
|
||||
final ServerConnectionInfo info;
|
||||
|
||||
const ServerConnectionState({
|
||||
this.status = ConnectionStatus.disconnected,
|
||||
this.statusMessage = 'Non connesso',
|
||||
this.info = const ServerConnectionInfo(),
|
||||
});
|
||||
|
||||
bool get isConnected => status == ConnectionStatus.connected;
|
||||
bool get isConnecting => status == ConnectionStatus.connecting;
|
||||
|
||||
ServerConnectionState copyWith({
|
||||
ConnectionStatus? status,
|
||||
String? statusMessage,
|
||||
ServerConnectionInfo? info,
|
||||
}) {
|
||||
return ServerConnectionState(
|
||||
status: status ?? this.status,
|
||||
statusMessage: statusMessage ?? this.statusMessage,
|
||||
info: info ?? this.info,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, statusMessage, info];
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../domain/repositories/connection_repository.dart';
|
||||
import 'discovery_state.dart';
|
||||
|
||||
class DiscoveryCubit extends Cubit<DiscoveryState> {
|
||||
final ConnectionRepository _connectionRepository;
|
||||
|
||||
DiscoveryCubit(this._connectionRepository) : super(const DiscoveryState());
|
||||
|
||||
Future<void> scanForServers({Duration timeout = const Duration(seconds: 3)}) async {
|
||||
if (state.isScanning) return;
|
||||
emit(state.copyWith(isScanning: true, errorMessage: null));
|
||||
|
||||
try {
|
||||
final found = await _connectionRepository.discoverServers(timeout: timeout);
|
||||
emit(state.copyWith(isScanning: false, servers: found));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
isScanning: false,
|
||||
errorMessage: 'Errore durante la scansione della rete: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
emit(const DiscoveryState());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../domain/entities/discovered_server.dart';
|
||||
|
||||
class DiscoveryState extends Equatable {
|
||||
final bool isScanning;
|
||||
final List<DiscoveredServer> servers;
|
||||
final String? errorMessage;
|
||||
|
||||
const DiscoveryState({
|
||||
this.isScanning = false,
|
||||
this.servers = const [],
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
DiscoveryState copyWith({
|
||||
bool? isScanning,
|
||||
List<DiscoveredServer>? servers,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return DiscoveryState(
|
||||
isScanning: isScanning ?? this.isScanning,
|
||||
servers: servers ?? this.servers,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [isScanning, servers, errorMessage];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../domain/entities/server_connection_info.dart';
|
||||
import '../../domain/repositories/connection_repository.dart';
|
||||
import '../cubit/connection_cubit.dart';
|
||||
import '../cubit/connection_state.dart';
|
||||
import '../cubit/discovery_cubit.dart';
|
||||
import '../cubit/discovery_state.dart';
|
||||
import '../widgets/qr_pairing_modal.dart';
|
||||
|
||||
class ConnectScreen extends StatefulWidget {
|
||||
const ConnectScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ConnectScreen> createState() => _ConnectScreenState();
|
||||
}
|
||||
|
||||
class _ConnectScreenState extends State<ConnectScreen> {
|
||||
late final TextEditingController _ipController;
|
||||
late final TextEditingController _portController;
|
||||
late final TextEditingController _pinController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final info = context.read<ConnectionCubit>().state.info;
|
||||
_ipController = TextEditingController(text: info.ip);
|
||||
_portController = TextEditingController(text: info.port.toString());
|
||||
_pinController = TextEditingController(text: info.pin);
|
||||
|
||||
// Auto trigger Wi-Fi discovery
|
||||
context.read<DiscoveryCubit>().scanForServers();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ipController.dispose();
|
||||
_portController.dispose();
|
||||
_pinController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onManualConnect() {
|
||||
final ip = _ipController.text.trim();
|
||||
final port = int.tryParse(_portController.text.trim()) ?? 8765;
|
||||
final pin = _pinController.text.trim();
|
||||
|
||||
if (ip.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Inserisci un indirizzo IP valido del PC'),
|
||||
backgroundColor: AppTheme.error,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final info = ServerConnectionInfo(
|
||||
ip: ip,
|
||||
port: port,
|
||||
pin: pin,
|
||||
serverName: '',
|
||||
);
|
||||
|
||||
context.read<ConnectionCubit>().connect(info);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Connessione a $ip:$port in corso...'),
|
||||
backgroundColor: AppTheme.primary,
|
||||
),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Connessione PC'),
|
||||
),
|
||||
body: BlocConsumer<ConnectionCubit, ServerConnectionState>(
|
||||
listener: (context, state) {
|
||||
if (state.info.ip != _ipController.text && state.info.ip.isNotEmpty) {
|
||||
_ipController.text = state.info.ip;
|
||||
_portController.text = state.info.port.toString();
|
||||
_pinController.text = state.info.pin;
|
||||
}
|
||||
},
|
||||
builder: (context, connectionState) {
|
||||
final isConnected = connectionState.isConnected;
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
||||
children: [
|
||||
// Hero Status Card
|
||||
_buildStatusCard(connectionState),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Method 1: QR Code
|
||||
FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: AppTheme.primary,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
|
||||
),
|
||||
icon: const Icon(Icons.qr_code_scanner_rounded, size: 22),
|
||||
label: const Text(
|
||||
'Inquadra QR Code sul PC',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
onPressed: () {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (_) => const QrPairingModal(),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// Method 2: Wi-Fi Discovery
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
const Text(
|
||||
'PC Rilevati in Wi-Fi',
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppTheme.darkTextPrimary,
|
||||
),
|
||||
),
|
||||
BlocBuilder<DiscoveryCubit, DiscoveryState>(
|
||||
builder: (context, discoveryState) {
|
||||
return IconButton(
|
||||
icon: discoveryState.isScanning
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: AppTheme.primary),
|
||||
)
|
||||
: const Icon(Icons.refresh_rounded, size: 20),
|
||||
tooltip: 'Aggiorna ricerca',
|
||||
onPressed: discoveryState.isScanning
|
||||
? null
|
||||
: () => context.read<DiscoveryCubit>().scanForServers(),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
|
||||
BlocBuilder<DiscoveryCubit, DiscoveryState>(
|
||||
builder: (context, discoveryState) {
|
||||
if (discoveryState.isScanning && discoveryState.servers.isEmpty) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.darkCard,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppTheme.darkBorder),
|
||||
),
|
||||
child: const Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Ricerca server PC in corso sulla rete...',
|
||||
style: TextStyle(color: AppTheme.darkTextSecondary, fontSize: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (discoveryState.servers.isEmpty) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.darkCard.withValues(alpha: 0.5),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppTheme.darkBorder),
|
||||
),
|
||||
child: const Text(
|
||||
'Nessun server PC rilevato automaticamente sulla rete.\nAssicurati che il programma sul PC sia avviato e connesso allo stesso Wi-Fi.',
|
||||
style: TextStyle(color: AppTheme.darkTextSecondary, fontSize: 13, height: 1.4),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: discoveryState.servers.map((srv) {
|
||||
final isCurrent = isConnected &&
|
||||
connectionState.info.ip == srv.ip &&
|
||||
connectionState.info.port == srv.port;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: const Icon(Icons.computer_rounded, color: AppTheme.primary),
|
||||
),
|
||||
title: Text(
|
||||
srv.serverName,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${srv.ip}:${srv.port} ${srv.pinRequired ? "• Richiede PIN" : ""}',
|
||||
style: const TextStyle(fontSize: 12, color: AppTheme.darkTextSecondary),
|
||||
),
|
||||
trailing: isCurrent
|
||||
? const Chip(
|
||||
label: Text('Connesso', style: TextStyle(fontSize: 12, color: AppTheme.success)),
|
||||
backgroundColor: Color(0xFF064E3B),
|
||||
side: BorderSide.none,
|
||||
)
|
||||
: FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
|
||||
),
|
||||
onPressed: () {
|
||||
context.read<ConnectionCubit>().connect(
|
||||
ServerConnectionInfo(
|
||||
ip: srv.ip,
|
||||
port: srv.port,
|
||||
pin: _pinController.text.trim(),
|
||||
serverName: srv.serverName,
|
||||
),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Connetti'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// Method 3: Manual Setup
|
||||
const Text(
|
||||
'Configurazione Manuale',
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppTheme.darkTextPrimary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextField(
|
||||
controller: _ipController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Indirizzo IP del PC',
|
||||
hintText: 'Es. 192.168.1.100',
|
||||
prefixIcon: Icon(Icons.lan_outlined, size: 20),
|
||||
),
|
||||
keyboardType: TextInputType.url,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: TextField(
|
||||
controller: _portController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Porta',
|
||||
hintText: '8765',
|
||||
prefixIcon: Icon(Icons.tag_rounded, size: 20),
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: TextField(
|
||||
controller: _pinController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'PIN (se impostato)',
|
||||
hintText: 'Codice PIN',
|
||||
prefixIcon: Icon(Icons.lock_outline_rounded, size: 20),
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
obscureText: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
icon: const Icon(Icons.save_rounded, size: 20),
|
||||
label: const Text('Salva e Connetti Manualmente'),
|
||||
onPressed: _onManualConnect,
|
||||
),
|
||||
|
||||
if (isConnected) ...[
|
||||
const SizedBox(height: 16),
|
||||
TextButton.icon(
|
||||
style: TextButton.styleFrom(foregroundColor: AppTheme.error),
|
||||
icon: const Icon(Icons.link_off_rounded, size: 20),
|
||||
label: const Text('Disconnetti dal PC'),
|
||||
onPressed: () {
|
||||
context.read<ConnectionCubit>().disconnect();
|
||||
},
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusCard(ServerConnectionState state) {
|
||||
Color badgeColor;
|
||||
IconData badgeIcon;
|
||||
|
||||
switch (state.status) {
|
||||
case ConnectionStatus.connected:
|
||||
badgeColor = AppTheme.success;
|
||||
badgeIcon = Icons.check_circle_rounded;
|
||||
break;
|
||||
case ConnectionStatus.connecting:
|
||||
badgeColor = AppTheme.warning;
|
||||
badgeIcon = Icons.sync_rounded;
|
||||
break;
|
||||
case ConnectionStatus.error:
|
||||
badgeColor = AppTheme.error;
|
||||
badgeIcon = Icons.error_outline_rounded;
|
||||
break;
|
||||
case ConnectionStatus.disconnected:
|
||||
badgeColor = AppTheme.darkTextSecondary;
|
||||
badgeIcon = Icons.cloud_off_rounded;
|
||||
break;
|
||||
}
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.darkCard,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: badgeColor.withValues(alpha: 0.4), width: 1.5),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: badgeColor.withValues(alpha: 0.1),
|
||||
blurRadius: 16,
|
||||
spreadRadius: 2,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: badgeColor.withValues(alpha: 0.15),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(badgeIcon, color: badgeColor, size: 28),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
state.info.displayName,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppTheme.darkTextPrimary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
state.statusMessage,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: badgeColor,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../domain/repositories/connection_repository.dart';
|
||||
import '../cubit/connection_cubit.dart';
|
||||
import '../cubit/connection_state.dart';
|
||||
import '../screens/connect_screen.dart';
|
||||
|
||||
class ConnectionStatusChip extends StatelessWidget {
|
||||
const ConnectionStatusChip({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<ConnectionCubit, ServerConnectionState>(
|
||||
builder: (context, state) {
|
||||
Color dotColor;
|
||||
String label;
|
||||
|
||||
switch (state.status) {
|
||||
case ConnectionStatus.connected:
|
||||
dotColor = AppTheme.success;
|
||||
label = state.info.displayName;
|
||||
break;
|
||||
case ConnectionStatus.connecting:
|
||||
dotColor = AppTheme.warning;
|
||||
label = 'Connessione...';
|
||||
break;
|
||||
case ConnectionStatus.error:
|
||||
dotColor = AppTheme.error;
|
||||
label = 'Errore PIN/Rete';
|
||||
break;
|
||||
case ConnectionStatus.disconnected:
|
||||
dotColor = AppTheme.darkTextSecondary;
|
||||
label = 'Non connesso';
|
||||
break;
|
||||
}
|
||||
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const ConnectScreen()),
|
||||
);
|
||||
},
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.darkCard.withValues(alpha: 0.85),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: dotColor.withValues(alpha: 0.4),
|
||||
width: 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.2),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: dotColor,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: dotColor.withValues(alpha: 0.6),
|
||||
blurRadius: 4,
|
||||
spreadRadius: 1,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 130),
|
||||
child: Text(
|
||||
label,
|
||||
style: const TextStyle(
|
||||
color: AppTheme.darkTextPrimary,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
const Icon(
|
||||
Icons.arrow_forward_ios_rounded,
|
||||
size: 10,
|
||||
color: AppTheme.darkTextSecondary,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../domain/entities/server_connection_info.dart';
|
||||
import '../cubit/connection_cubit.dart';
|
||||
|
||||
class QrPairingModal extends StatelessWidget {
|
||||
const QrPairingModal({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
height: MediaQuery.of(context).size.height * 0.75,
|
||||
decoration: const BoxDecoration(
|
||||
color: AppTheme.darkSurface,
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
margin: const EdgeInsets.only(top: 12, bottom: 8),
|
||||
width: 40,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.darkBorder,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.qr_code_scanner, color: AppTheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
const Text(
|
||||
'Inquadra QR Code del Server',
|
||||
style: TextStyle(
|
||||
fontSize: 17,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppTheme.darkTextPrimary,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 4),
|
||||
child: Text(
|
||||
'Inquadra il codice QR mostrato nel terminale o nella dashboard web del PC.',
|
||||
style: TextStyle(color: AppTheme.darkTextSecondary, fontSize: 13),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: MobileScanner(
|
||||
onDetect: (capture) {
|
||||
final barcode = capture.barcodes.firstOrNull;
|
||||
if (barcode?.rawValue == null) return;
|
||||
final val = barcode!.rawValue!;
|
||||
|
||||
try {
|
||||
final json = jsonDecode(val) as Map<String, dynamic>;
|
||||
final ip = json['ip'] as String?;
|
||||
final port = json['port'] as int? ?? 8765;
|
||||
final pin = json['pin'] as String? ?? '';
|
||||
final name = json['name'] as String? ?? 'PC Server';
|
||||
|
||||
if (ip != null && ip.isNotEmpty) {
|
||||
context.read<ConnectionCubit>().connect(
|
||||
ServerConnectionInfo(
|
||||
ip: ip,
|
||||
port: port,
|
||||
pin: pin,
|
||||
serverName: name,
|
||||
),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
return;
|
||||
}
|
||||
} catch (_) {
|
||||
final uri = Uri.tryParse(val);
|
||||
if (uri != null && uri.host.isNotEmpty) {
|
||||
context.read<ConnectionCubit>().connect(
|
||||
ServerConnectionInfo(
|
||||
ip: uri.host,
|
||||
port: uri.port != 0 ? uri.port : 8765,
|
||||
pin: '',
|
||||
serverName: 'PC Server',
|
||||
),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../../core/constants/app_constants.dart';
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
|
||||
class ScanHistoryDataSource {
|
||||
final SharedPreferences _prefs;
|
||||
|
||||
ScanHistoryDataSource(this._prefs);
|
||||
|
||||
List<ScanRecord> loadHistory() {
|
||||
final list = _prefs.getStringList(AppConstants.keyHistory) ?? [];
|
||||
return list
|
||||
.map((str) {
|
||||
try {
|
||||
return ScanRecord.fromJson(jsonDecode(str) as Map<String, dynamic>);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.whereType<ScanRecord>()
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> saveRecord(ScanRecord record) async {
|
||||
final history = loadHistory();
|
||||
history.insert(0, record);
|
||||
// Keep max 250 items
|
||||
if (history.length > 250) {
|
||||
history.removeRange(250, history.length);
|
||||
}
|
||||
final encoded = history.map((e) => jsonEncode(e.toJson())).toList();
|
||||
await _prefs.setStringList(AppConstants.keyHistory, encoded);
|
||||
}
|
||||
|
||||
Future<void> deleteRecord(String id) async {
|
||||
final history = loadHistory()..removeWhere((item) => item.id == id);
|
||||
final encoded = history.map((e) => jsonEncode(e.toJson())).toList();
|
||||
await _prefs.setStringList(AppConstants.keyHistory, encoded);
|
||||
}
|
||||
|
||||
Future<void> clearHistory() async {
|
||||
await _prefs.remove(AppConstants.keyHistory);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
import '../../domain/repositories/scan_repository.dart';
|
||||
import '../datasources/scan_history_datasource.dart';
|
||||
|
||||
class ScanRepositoryImpl implements ScanRepository {
|
||||
final ScanHistoryDataSource _dataSource;
|
||||
|
||||
ScanRepositoryImpl(this._dataSource);
|
||||
|
||||
@override
|
||||
Future<List<ScanRecord>> loadHistory() async {
|
||||
return _dataSource.loadHistory();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveRecord(ScanRecord record) async {
|
||||
await _dataSource.saveRecord(record);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deleteRecord(String id) async {
|
||||
await _dataSource.deleteRecord(id);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearHistory() async {
|
||||
await _dataSource.clearHistory();
|
||||
}
|
||||
}
|
||||
|
||||
+26
-4
@@ -1,16 +1,18 @@
|
||||
class ScanRecord {
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class ScanRecord extends Equatable {
|
||||
final String id;
|
||||
final String code;
|
||||
final String format;
|
||||
final DateTime timestamp;
|
||||
final bool sentSuccessfully;
|
||||
|
||||
ScanRecord({
|
||||
const ScanRecord({
|
||||
required this.id,
|
||||
required this.code,
|
||||
required this.format,
|
||||
required this.timestamp,
|
||||
this.sentSuccessfully = true,
|
||||
required this.sentSuccessfully,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
@@ -28,6 +30,26 @@ class ScanRecord {
|
||||
timestamp: json['timestamp'] != null
|
||||
? DateTime.tryParse(json['timestamp'] as String) ?? DateTime.now()
|
||||
: DateTime.now(),
|
||||
sentSuccessfully: json['sentSuccessfully'] as bool? ?? true,
|
||||
sentSuccessfully: json['sentSuccessfully'] as bool? ?? false,
|
||||
);
|
||||
|
||||
ScanRecord copyWith({
|
||||
String? id,
|
||||
String? code,
|
||||
String? format,
|
||||
DateTime? timestamp,
|
||||
bool? sentSuccessfully,
|
||||
}) {
|
||||
return ScanRecord(
|
||||
id: id ?? this.id,
|
||||
code: code ?? this.code,
|
||||
format: format ?? this.format,
|
||||
timestamp: timestamp ?? this.timestamp,
|
||||
sentSuccessfully: sentSuccessfully ?? this.sentSuccessfully,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, code, format, timestamp, sentSuccessfully];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import '../entities/scan_record.dart';
|
||||
|
||||
abstract class ScanRepository {
|
||||
Future<List<ScanRecord>> loadHistory();
|
||||
Future<void> saveRecord(ScanRecord record);
|
||||
Future<void> clearHistory();
|
||||
Future<void> deleteRecord(String id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
import '../../domain/repositories/scan_repository.dart';
|
||||
import 'history_state.dart';
|
||||
|
||||
class HistoryCubit extends Cubit<HistoryState> {
|
||||
final ScanRepository _scanRepository;
|
||||
|
||||
HistoryCubit(this._scanRepository) : super(const HistoryState());
|
||||
|
||||
Future<void> loadHistory() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
final items = await _scanRepository.loadHistory();
|
||||
emit(state.copyWith(history: items, isLoading: false));
|
||||
} catch (_) {
|
||||
emit(state.copyWith(isLoading: false));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addScan(ScanRecord record) async {
|
||||
final updated = [record, ...state.history];
|
||||
emit(state.copyWith(history: updated));
|
||||
await _scanRepository.saveRecord(record);
|
||||
}
|
||||
|
||||
Future<void> deleteScan(String id) async {
|
||||
final updated = state.history.where((e) => e.id != id).toList();
|
||||
emit(state.copyWith(history: updated));
|
||||
await _scanRepository.deleteRecord(id);
|
||||
}
|
||||
|
||||
Future<void> clearHistory() async {
|
||||
emit(state.copyWith(history: []));
|
||||
await _scanRepository.clearHistory();
|
||||
}
|
||||
|
||||
void setSearchQuery(String query) {
|
||||
emit(state.copyWith(searchQuery: query.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
|
||||
class HistoryState extends Equatable {
|
||||
final List<ScanRecord> history;
|
||||
final String searchQuery;
|
||||
final bool isLoading;
|
||||
|
||||
const HistoryState({
|
||||
this.history = const [],
|
||||
this.searchQuery = '',
|
||||
this.isLoading = false,
|
||||
});
|
||||
|
||||
List<ScanRecord> get filteredHistory {
|
||||
if (searchQuery.isEmpty) return history;
|
||||
final q = searchQuery.toLowerCase();
|
||||
return history.where((item) => item.code.toLowerCase().contains(q)).toList();
|
||||
}
|
||||
|
||||
HistoryState copyWith({
|
||||
List<ScanRecord>? history,
|
||||
String? searchQuery,
|
||||
bool? isLoading,
|
||||
}) {
|
||||
return HistoryState(
|
||||
history: history ?? this.history,
|
||||
searchQuery: searchQuery ?? this.searchQuery,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [history, searchQuery, isLoading];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/services/feedback_service.dart';
|
||||
import '../../../connection/presentation/cubit/connection_cubit.dart';
|
||||
import '../../../settings/presentation/cubit/settings_cubit.dart';
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
import 'history_cubit.dart';
|
||||
import 'scanner_state.dart';
|
||||
|
||||
class ScannerCubit extends Cubit<ScannerState> {
|
||||
final ConnectionCubit connectionCubit;
|
||||
final SettingsCubit settingsCubit;
|
||||
final HistoryCubit historyCubit;
|
||||
final FeedbackService feedbackService;
|
||||
|
||||
ScannerCubit({
|
||||
required this.connectionCubit,
|
||||
required this.settingsCubit,
|
||||
required this.historyCubit,
|
||||
required this.feedbackService,
|
||||
}) : super(ScannerState());
|
||||
|
||||
void toggleTorch() {
|
||||
emit(state.copyWith(isTorchOn: !state.isTorchOn));
|
||||
}
|
||||
|
||||
void toggleCamera() {
|
||||
emit(state.copyWith(isFrontCamera: !state.isFrontCamera));
|
||||
}
|
||||
|
||||
Future<void> processBarcode(String rawValue, {String format = 'Barcode'}) async {
|
||||
final cleanCode = rawValue.trim();
|
||||
if (cleanCode.isEmpty) return;
|
||||
|
||||
final now = DateTime.now();
|
||||
final isSameCode = cleanCode == state.lastScannedValue;
|
||||
final durationSinceLast = now.difference(state.lastScannedTime);
|
||||
final continuous = settingsCubit.state.settings.continuousMode;
|
||||
|
||||
// Minimum debounce interval
|
||||
final minInterval = isSameCode
|
||||
? (continuous ? const Duration(milliseconds: 1000) : const Duration(milliseconds: 1800))
|
||||
: const Duration(milliseconds: 600);
|
||||
|
||||
if (durationSinceLast < minInterval || state.isProcessing) {
|
||||
return;
|
||||
}
|
||||
|
||||
emit(state.copyWith(
|
||||
isProcessing: true,
|
||||
lastScannedValue: cleanCode,
|
||||
lastScannedTime: now,
|
||||
));
|
||||
|
||||
final settings = settingsCubit.state.settings;
|
||||
await feedbackService.triggerScanFeedback(
|
||||
sound: settings.sound,
|
||||
vibrate: settings.vibrate,
|
||||
);
|
||||
|
||||
final success = await connectionCubit.sendCode(
|
||||
code: cleanCode,
|
||||
suffix: settings.suffix,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
await feedbackService.triggerSuccess();
|
||||
}
|
||||
|
||||
final record = ScanRecord(
|
||||
id: DateTime.now().millisecondsSinceEpoch.toString(),
|
||||
code: cleanCode,
|
||||
format: format,
|
||||
timestamp: now,
|
||||
sentSuccessfully: success,
|
||||
);
|
||||
|
||||
await historyCubit.addScan(record);
|
||||
|
||||
emit(state.copyWith(
|
||||
isProcessing: false,
|
||||
lastScan: record,
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> resendScan(ScanRecord record) async {
|
||||
final settings = settingsCubit.state.settings;
|
||||
await feedbackService.triggerScanFeedback(
|
||||
sound: settings.sound,
|
||||
vibrate: settings.vibrate,
|
||||
);
|
||||
|
||||
final success = await connectionCubit.sendCode(
|
||||
code: record.code,
|
||||
suffix: settings.suffix,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
await feedbackService.triggerSuccess();
|
||||
}
|
||||
|
||||
final updated = record.copyWith(
|
||||
timestamp: DateTime.now(),
|
||||
sentSuccessfully: success,
|
||||
);
|
||||
|
||||
await historyCubit.addScan(updated);
|
||||
emit(state.copyWith(lastScan: updated));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
|
||||
class ScannerState extends Equatable {
|
||||
final ScanRecord? lastScan;
|
||||
final bool isTorchOn;
|
||||
final bool isFrontCamera;
|
||||
final bool isProcessing;
|
||||
final String? lastScannedValue;
|
||||
final DateTime lastScannedTime;
|
||||
|
||||
ScannerState({
|
||||
this.lastScan,
|
||||
this.isTorchOn = false,
|
||||
this.isFrontCamera = false,
|
||||
this.isProcessing = false,
|
||||
this.lastScannedValue,
|
||||
DateTime? lastScannedTime,
|
||||
}) : lastScannedTime = lastScannedTime ?? DateTime.fromMillisecondsSinceEpoch(0);
|
||||
|
||||
ScannerState copyWith({
|
||||
ScanRecord? lastScan,
|
||||
bool? isTorchOn,
|
||||
bool? isFrontCamera,
|
||||
bool? isProcessing,
|
||||
String? lastScannedValue,
|
||||
DateTime? lastScannedTime,
|
||||
}) {
|
||||
return ScannerState(
|
||||
lastScan: lastScan ?? this.lastScan,
|
||||
isTorchOn: isTorchOn ?? this.isTorchOn,
|
||||
isFrontCamera: isFrontCamera ?? this.isFrontCamera,
|
||||
isProcessing: isProcessing ?? this.isProcessing,
|
||||
lastScannedValue: lastScannedValue ?? this.lastScannedValue,
|
||||
lastScannedTime: lastScannedTime ?? this.lastScannedTime,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
lastScan,
|
||||
isTorchOn,
|
||||
isFrontCamera,
|
||||
isProcessing,
|
||||
lastScannedValue,
|
||||
lastScannedTime,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
import '../cubit/history_cubit.dart';
|
||||
import '../cubit/history_state.dart';
|
||||
import '../cubit/scanner_cubit.dart';
|
||||
|
||||
class HistoryScreen extends StatefulWidget {
|
||||
const HistoryScreen({super.key});
|
||||
|
||||
@override
|
||||
State<HistoryScreen> createState() => _HistoryScreenState();
|
||||
}
|
||||
|
||||
class _HistoryScreenState extends State<HistoryScreen> {
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _confirmClear() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Cancellare Cronologia?'),
|
||||
content: const Text(
|
||||
'Tutti i codici salvati nella cronologia su questo dispositivo verranno rimossi.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: AppTheme.error),
|
||||
onPressed: () {
|
||||
context.read<HistoryCubit>().clearHistory();
|
||||
Navigator.pop(ctx);
|
||||
},
|
||||
child: const Text('Cancella Tutto'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Cronologia Scansioni'),
|
||||
actions: [
|
||||
BlocBuilder<HistoryCubit, HistoryState>(
|
||||
builder: (context, state) {
|
||||
if (state.history.isEmpty) return const SizedBox.shrink();
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.delete_sweep_rounded),
|
||||
tooltip: 'Cancella cronologia',
|
||||
onPressed: _confirmClear,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: BlocBuilder<HistoryCubit, HistoryState>(
|
||||
builder: (context, state) {
|
||||
final items = state.filteredHistory;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
if (state.history.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
|
||||
child: TextField(
|
||||
controller: _searchController,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Cerca tra i codici...',
|
||||
prefixIcon: const Icon(Icons.search_rounded, size: 20),
|
||||
suffixIcon: state.searchQuery.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.clear_rounded, size: 18),
|
||||
onPressed: () {
|
||||
_searchController.clear();
|
||||
context.read<HistoryCubit>().setSearchQuery('');
|
||||
},
|
||||
)
|
||||
: null,
|
||||
),
|
||||
onChanged: (val) {
|
||||
context.read<HistoryCubit>().setSearchQuery(val);
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: items.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
state.searchQuery.isEmpty
|
||||
? Icons.history_toggle_off_rounded
|
||||
: Icons.search_off_rounded,
|
||||
size: 64,
|
||||
color: AppTheme.darkTextSecondary.withValues(alpha: 0.5),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
state.searchQuery.isEmpty
|
||||
? 'Nessuna scansione in memoria'
|
||||
: 'Nessun risultato per "${state.searchQuery}"',
|
||||
style: const TextStyle(
|
||||
color: AppTheme.darkTextSecondary,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.separated(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
itemCount: items.length,
|
||||
separatorBuilder: (context, index) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return _HistoryTile(item: item);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HistoryTile extends StatelessWidget {
|
||||
final ScanRecord item;
|
||||
|
||||
const _HistoryTile({required this.item});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isSuccess = item.sentSuccessfully;
|
||||
|
||||
return Dismissible(
|
||||
key: Key(item.id),
|
||||
direction: DismissDirection.endToStart,
|
||||
background: Container(
|
||||
alignment: Alignment.centerRight,
|
||||
padding: const EdgeInsets.only(right: 20),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.error.withValues(alpha: 0.8),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: const Icon(Icons.delete_rounded, color: Colors.white),
|
||||
),
|
||||
onDismissed: (_) {
|
||||
context.read<HistoryCubit>().deleteScan(item.id);
|
||||
},
|
||||
child: Card(
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: (isSuccess ? AppTheme.success : AppTheme.warning)
|
||||
.withValues(alpha: 0.15),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
isSuccess ? Icons.check_circle_rounded : Icons.warning_amber_rounded,
|
||||
color: isSuccess ? AppTheme.success : AppTheme.warning,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
item.code,
|
||||
style: const TextStyle(
|
||||
fontFamily: 'monospace',
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${item.format} • ${item.timestamp.hour.toString().padLeft(2, '0')}:${item.timestamp.minute.toString().padLeft(2, '0')}:${item.timestamp.second.toString().padLeft(2, '0')} - ${item.timestamp.day}/${item.timestamp.month}/${item.timestamp.year}',
|
||||
style: const TextStyle(fontSize: 12, color: AppTheme.darkTextSecondary),
|
||||
),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy_rounded, size: 20),
|
||||
tooltip: 'Copia codice',
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: item.code));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Copiato negli appunti'),
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.send_rounded, size: 20),
|
||||
tooltip: 'Invia di nuovo al PC',
|
||||
color: AppTheme.primary,
|
||||
onPressed: () {
|
||||
context.read<ScannerCubit>().resendScan(item);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Inviato "${item.code}" al PC'),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../../connection/presentation/widgets/connection_status_chip.dart';
|
||||
import '../../../settings/presentation/screens/settings_screen.dart';
|
||||
import '../cubit/history_cubit.dart';
|
||||
import '../cubit/history_state.dart';
|
||||
import '../cubit/scanner_cubit.dart';
|
||||
import '../cubit/scanner_state.dart';
|
||||
import '../widgets/last_scan_card.dart';
|
||||
import '../widgets/manual_input_dialog.dart';
|
||||
import '../widgets/scanner_overlay.dart';
|
||||
import 'history_screen.dart';
|
||||
|
||||
class ScannerScreen extends StatefulWidget {
|
||||
const ScannerScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ScannerScreen> createState() => _ScannerScreenState();
|
||||
}
|
||||
|
||||
class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserver {
|
||||
late MobileScannerController _scannerController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_scannerController = MobileScannerController(
|
||||
detectionSpeed: DetectionSpeed.normal,
|
||||
facing: CameraFacing.back,
|
||||
torchEnabled: false,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_scannerController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (!_scannerController.value.isInitialized) return;
|
||||
if (state == AppLifecycleState.inactive || state == AppLifecycleState.paused) {
|
||||
_scannerController.stop();
|
||||
} else if (state == AppLifecycleState.resumed) {
|
||||
_scannerController.start();
|
||||
}
|
||||
}
|
||||
|
||||
void _onDetect(BarcodeCapture capture) {
|
||||
final barcodes = capture.barcodes;
|
||||
if (barcodes.isEmpty) return;
|
||||
|
||||
final first = barcodes.first;
|
||||
final rawValue = first.rawValue ?? first.displayValue;
|
||||
if (rawValue == null || rawValue.trim().isEmpty) return;
|
||||
|
||||
final formatName = first.format.name.replaceAll('BarcodeFormat.', '');
|
||||
context.read<ScannerCubit>().processBarcode(rawValue, format: formatName);
|
||||
}
|
||||
|
||||
void _toggleTorch() {
|
||||
_scannerController.toggleTorch();
|
||||
context.read<ScannerCubit>().toggleTorch();
|
||||
}
|
||||
|
||||
void _switchCamera() {
|
||||
_scannerController.switchCamera();
|
||||
context.read<ScannerCubit>().toggleCamera();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
body: BlocBuilder<ScannerCubit, ScannerState>(
|
||||
builder: (context, scannerState) {
|
||||
final lastScan = scannerState.lastScan;
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// 1. Camera Viewfinder
|
||||
MobileScanner(
|
||||
controller: _scannerController,
|
||||
onDetect: _onDetect,
|
||||
),
|
||||
|
||||
// 2. High-Tech Laser Reticle Overlay
|
||||
const ScannerOverlay(),
|
||||
|
||||
// 3. Top Floating Glass Control Bar
|
||||
SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
// Torch Toggle
|
||||
_CircleGlassButton(
|
||||
icon: scannerState.isTorchOn
|
||||
? Icons.flash_on_rounded
|
||||
: Icons.flash_off_rounded,
|
||||
color: scannerState.isTorchOn ? Colors.amber : Colors.white,
|
||||
tooltip: 'Torcia',
|
||||
onPressed: _toggleTorch,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// Camera Flip
|
||||
_CircleGlassButton(
|
||||
icon: Icons.flip_camera_ios_rounded,
|
||||
tooltip: 'Inverti Fotocamera',
|
||||
onPressed: _switchCamera,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// Center: Connection Status Chip
|
||||
const Expanded(
|
||||
child: Center(
|
||||
child: ConnectionStatusChip(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// History Button with Badge
|
||||
BlocBuilder<HistoryCubit, HistoryState>(
|
||||
builder: (context, historyState) {
|
||||
final count = historyState.history.length;
|
||||
return Badge(
|
||||
isLabelVisible: count > 0,
|
||||
label: Text(
|
||||
count > 99 ? '99+' : count.toString(),
|
||||
style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold),
|
||||
),
|
||||
backgroundColor: AppTheme.primary,
|
||||
textColor: Colors.white,
|
||||
offset: const Offset(-2, 2),
|
||||
child: _CircleGlassButton(
|
||||
icon: Icons.history_rounded,
|
||||
tooltip: 'Cronologia',
|
||||
onPressed: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const HistoryScreen()),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// Settings Button
|
||||
_CircleGlassButton(
|
||||
icon: Icons.settings_outlined,
|
||||
tooltip: 'Impostazioni',
|
||||
onPressed: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const SettingsScreen()),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 4. Floating Action Button for Manual Entry
|
||||
Positioned(
|
||||
bottom: lastScan != null ? 120 : 32,
|
||||
right: 20,
|
||||
child: FloatingActionButton.extended(
|
||||
heroTag: 'scanner_manual_input',
|
||||
backgroundColor: AppTheme.darkCard,
|
||||
foregroundColor: AppTheme.primary,
|
||||
elevation: 6,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: const BorderSide(color: AppTheme.darkBorder, width: 1),
|
||||
),
|
||||
icon: const Icon(Icons.keyboard_rounded),
|
||||
label: const Text(
|
||||
'Manuale',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
onPressed: () => ManualInputDialog.show(context),
|
||||
),
|
||||
),
|
||||
|
||||
// 5. Bottom Last Scan Card
|
||||
if (lastScan != null)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 24,
|
||||
child: LastScanCard(record: lastScan),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CircleGlassButton extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final VoidCallback onPressed;
|
||||
final String tooltip;
|
||||
final Color color;
|
||||
|
||||
const _CircleGlassButton({
|
||||
required this.icon,
|
||||
required this.onPressed,
|
||||
required this.tooltip,
|
||||
this.color = Colors.white,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.darkCard.withValues(alpha: 0.8),
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: AppTheme.darkBorder.withValues(alpha: 0.6), width: 1),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.25),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: IconButton(
|
||||
icon: Icon(icon, color: color, size: 20),
|
||||
tooltip: tooltip,
|
||||
onPressed: onPressed,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../domain/entities/scan_record.dart';
|
||||
import '../cubit/scanner_cubit.dart';
|
||||
|
||||
class LastScanCard extends StatelessWidget {
|
||||
final ScanRecord record;
|
||||
|
||||
const LastScanCard({super.key, required this.record});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isSuccess = record.sentSuccessfully;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.darkCard.withValues(alpha: 0.95),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: isSuccess
|
||||
? AppTheme.success.withValues(alpha: 0.4)
|
||||
: AppTheme.warning.withValues(alpha: 0.4),
|
||||
width: 1.5,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.4),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: (isSuccess ? AppTheme.success : AppTheme.warning)
|
||||
.withValues(alpha: 0.15),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
isSuccess ? Icons.check_circle_rounded : Icons.warning_amber_rounded,
|
||||
color: isSuccess ? AppTheme.success : AppTheme.warning,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
record.format.toUpperCase(),
|
||||
style: const TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppTheme.secondary,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'${record.timestamp.hour.toString().padLeft(2, '0')}:${record.timestamp.minute.toString().padLeft(2, '0')}:${record.timestamp.second.toString().padLeft(2, '0')}',
|
||||
style: const TextStyle(fontSize: 11, color: AppTheme.darkTextSecondary),
|
||||
),
|
||||
if (!isSuccess) ...[
|
||||
const Spacer(),
|
||||
const Text(
|
||||
'Non inviato',
|
||||
style: TextStyle(fontSize: 11, color: AppTheme.warning),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
record.code,
|
||||
style: const TextStyle(
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppTheme.darkTextPrimary,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy_rounded, size: 20),
|
||||
tooltip: 'Copia',
|
||||
color: AppTheme.darkTextSecondary,
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: record.code));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Codice copiato negli appunti'),
|
||||
duration: Duration(seconds: 1),
|
||||
backgroundColor: AppTheme.darkCard,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.send_rounded, size: 20),
|
||||
tooltip: 'Invia di nuovo al PC',
|
||||
color: AppTheme.primary,
|
||||
onPressed: () {
|
||||
context.read<ScannerCubit>().resendScan(record);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../cubit/scanner_cubit.dart';
|
||||
|
||||
class ManualInputDialog extends StatefulWidget {
|
||||
const ManualInputDialog({super.key});
|
||||
|
||||
static Future<void> show(BuildContext context) {
|
||||
return showDialog(
|
||||
context: context,
|
||||
builder: (_) => BlocProvider.value(
|
||||
value: context.read<ScannerCubit>(),
|
||||
child: const ManualInputDialog(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
State<ManualInputDialog> createState() => _ManualInputDialogState();
|
||||
}
|
||||
|
||||
class _ManualInputDialogState extends State<ManualInputDialog> {
|
||||
late final TextEditingController _textController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_textController = TextEditingController();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_textController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
final code = _textController.text.trim();
|
||||
if (code.isNotEmpty) {
|
||||
context.read<ScannerCubit>().processBarcode(code, format: 'Manuale');
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Row(
|
||||
children: [
|
||||
Icon(Icons.keyboard_outlined, color: AppTheme.primary),
|
||||
SizedBox(width: 10),
|
||||
Text(
|
||||
'Digitazione Manuale',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Digita o incolla il codice da digitare in tempo reale sul PC:',
|
||||
style: TextStyle(fontSize: 13, color: AppTheme.darkTextSecondary),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextField(
|
||||
controller: _textController,
|
||||
autofocus: true,
|
||||
style: const TextStyle(fontFamily: 'monospace', fontSize: 16),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Es. 8001234567890 o ART-99',
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.paste_rounded, size: 20),
|
||||
tooltip: 'Incolla dagli appunti',
|
||||
onPressed: () async {
|
||||
final data = await Clipboard.getData('text/plain');
|
||||
if (data?.text != null) {
|
||||
_textController.text = data!.text!;
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
],
|
||||
),
|
||||
actionsPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
icon: const Icon(Icons.send_rounded, size: 18),
|
||||
label: const Text('Invia al PC'),
|
||||
onPressed: _submit,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
|
||||
class ScannerOverlay extends StatefulWidget {
|
||||
const ScannerOverlay({super.key});
|
||||
|
||||
@override
|
||||
State<ScannerOverlay> createState() => _ScannerOverlayState();
|
||||
}
|
||||
|
||||
class _ScannerOverlayState extends State<ScannerOverlay>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _animController;
|
||||
late Animation<double> _anim;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_animController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 2200),
|
||||
)..repeat(reverse: true);
|
||||
|
||||
_anim = CurvedAnimation(
|
||||
parent: _animController,
|
||||
curve: Curves.easeInOutSine,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_animController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final boxWidth = constraints.maxWidth * 0.84;
|
||||
final boxHeight = constraints.maxHeight * 0.38;
|
||||
final left = (constraints.maxWidth - boxWidth) / 2;
|
||||
final top = (constraints.maxHeight - boxHeight) / 2.3;
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// Dark semi-transparent cutout mask
|
||||
ColorFiltered(
|
||||
colorFilter: ColorFilter.mode(
|
||||
Colors.black.withValues(alpha: 0.65),
|
||||
BlendMode.srcOut,
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
Container(
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.transparent,
|
||||
),
|
||||
child: Container(
|
||||
margin: EdgeInsets.fromLTRB(
|
||||
left,
|
||||
top,
|
||||
left,
|
||||
constraints.maxHeight - top - boxHeight,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Corner Reticles & Outer Border
|
||||
Positioned(
|
||||
left: left,
|
||||
top: top,
|
||||
width: boxWidth,
|
||||
height: boxHeight,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
border: Border.all(
|
||||
color: AppTheme.primary.withValues(alpha: 0.35),
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Corner Accents (High-Tech look)
|
||||
_CornerAccents(left: left, top: top, width: boxWidth, height: boxHeight),
|
||||
|
||||
// Animated Laser Beam
|
||||
AnimatedBuilder(
|
||||
animation: _anim,
|
||||
builder: (context, child) {
|
||||
final beamTop = top + 14 + (_anim.value * (boxHeight - 28));
|
||||
return Positioned(
|
||||
left: left + 14,
|
||||
top: beamTop,
|
||||
width: boxWidth - 28,
|
||||
height: 2.5,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
AppTheme.primary.withValues(alpha: 0.1),
|
||||
AppTheme.primary,
|
||||
Colors.cyanAccent,
|
||||
AppTheme.primary,
|
||||
AppTheme.primary.withValues(alpha: 0.1),
|
||||
],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: AppTheme.primary.withValues(alpha: 0.8),
|
||||
blurRadius: 8,
|
||||
spreadRadius: 1.5,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
// Subtle helper text
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: top + boxHeight + 20,
|
||||
child: const Text(
|
||||
'Inquadra codice a barre o QR code',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w500,
|
||||
letterSpacing: 0.3,
|
||||
shadows: [
|
||||
Shadow(color: Colors.black, blurRadius: 6),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CornerAccents extends StatelessWidget {
|
||||
final double left;
|
||||
final double top;
|
||||
final double width;
|
||||
final double height;
|
||||
|
||||
const _CornerAccents({
|
||||
required this.left,
|
||||
required this.top,
|
||||
required this.width,
|
||||
required this.height,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const cornerSize = 24.0;
|
||||
const strokeWidth = 3.5;
|
||||
const cornerRadius = 18.0;
|
||||
const color = AppTheme.primary;
|
||||
|
||||
return Positioned(
|
||||
left: left,
|
||||
top: top,
|
||||
width: width,
|
||||
height: height,
|
||||
child: CustomPaint(
|
||||
painter: _CornersPainter(
|
||||
color: color,
|
||||
cornerSize: cornerSize,
|
||||
strokeWidth: strokeWidth,
|
||||
radius: cornerRadius,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CornersPainter extends CustomPainter {
|
||||
final Color color;
|
||||
final double cornerSize;
|
||||
final double strokeWidth;
|
||||
final double radius;
|
||||
|
||||
_CornersPainter({
|
||||
required this.color,
|
||||
required this.cornerSize,
|
||||
required this.strokeWidth,
|
||||
required this.radius,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final paint = Paint()
|
||||
..color = color
|
||||
..strokeWidth = strokeWidth
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeCap = StrokeCap.round;
|
||||
|
||||
// Top-Left
|
||||
final pathTL = Path()
|
||||
..moveTo(0, cornerSize)
|
||||
..lineTo(0, radius)
|
||||
..quadraticBezierTo(0, 0, radius, 0)
|
||||
..lineTo(cornerSize, 0);
|
||||
canvas.drawPath(pathTL, paint);
|
||||
|
||||
// Top-Right
|
||||
final pathTR = Path()
|
||||
..moveTo(size.width - cornerSize, 0)
|
||||
..lineTo(size.width - radius, 0)
|
||||
..quadraticBezierTo(size.width, 0, size.width, radius)
|
||||
..lineTo(size.width, cornerSize);
|
||||
canvas.drawPath(pathTR, paint);
|
||||
|
||||
// Bottom-Left
|
||||
final pathBL = Path()
|
||||
..moveTo(0, size.height - cornerSize)
|
||||
..lineTo(0, size.height - radius)
|
||||
..quadraticBezierTo(0, size.height, radius, size.height)
|
||||
..lineTo(cornerSize, size.height);
|
||||
canvas.drawPath(pathBL, paint);
|
||||
|
||||
// Bottom-Right
|
||||
final pathBR = Path()
|
||||
..moveTo(size.width - cornerSize, size.height)
|
||||
..lineTo(size.width - radius, size.height)
|
||||
..quadraticBezierTo(size.width, size.height, size.width, size.height - radius)
|
||||
..lineTo(size.width, size.height - cornerSize);
|
||||
canvas.drawPath(pathBR, paint);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../../core/constants/app_constants.dart';
|
||||
import '../../domain/entities/app_settings.dart';
|
||||
|
||||
class SettingsLocalDataSource {
|
||||
final SharedPreferences _prefs;
|
||||
|
||||
SettingsLocalDataSource(this._prefs);
|
||||
|
||||
AppSettings loadSettings() {
|
||||
final suffix = _prefs.getString(AppConstants.keySuffix) ?? AppConstants.suffixEnter;
|
||||
final continuous = _prefs.getBool(AppConstants.keyContinuous) ?? false;
|
||||
final vibrate = _prefs.getBool(AppConstants.keyVibrate) ?? true;
|
||||
final sound = _prefs.getBool(AppConstants.keySound) ?? true;
|
||||
|
||||
return AppSettings(
|
||||
suffix: suffix,
|
||||
continuousMode: continuous,
|
||||
vibrate: vibrate,
|
||||
sound: sound,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> saveSuffix(String suffix) async {
|
||||
await _prefs.setString(AppConstants.keySuffix, suffix);
|
||||
}
|
||||
|
||||
Future<void> saveContinuousMode(bool enabled) async {
|
||||
await _prefs.setBool(AppConstants.keyContinuous, enabled);
|
||||
}
|
||||
|
||||
Future<void> saveFeedbackToggles({required bool vibrate, required bool sound}) async {
|
||||
await _prefs.setBool(AppConstants.keyVibrate, vibrate);
|
||||
await _prefs.setBool(AppConstants.keySound, sound);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import '../../domain/entities/app_settings.dart';
|
||||
import '../../domain/repositories/settings_repository.dart';
|
||||
import '../datasources/settings_local_datasource.dart';
|
||||
|
||||
class SettingsRepositoryImpl implements SettingsRepository {
|
||||
final SettingsLocalDataSource _localDataSource;
|
||||
|
||||
SettingsRepositoryImpl(this._localDataSource);
|
||||
|
||||
@override
|
||||
Future<AppSettings> loadSettings() async {
|
||||
return _localDataSource.loadSettings();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveSuffix(String suffix) async {
|
||||
await _localDataSource.saveSuffix(suffix);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveContinuousMode(bool enabled) async {
|
||||
await _localDataSource.saveContinuousMode(enabled);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveFeedbackToggles({required bool vibrate, required bool sound}) async {
|
||||
await _localDataSource.saveFeedbackToggles(vibrate: vibrate, sound: sound);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class AppSettings extends Equatable {
|
||||
final String suffix; // 'enter', 'tab', 'none'
|
||||
final bool continuousMode;
|
||||
final bool vibrate;
|
||||
final bool sound;
|
||||
|
||||
const AppSettings({
|
||||
this.suffix = 'enter',
|
||||
this.continuousMode = false,
|
||||
this.vibrate = true,
|
||||
this.sound = true,
|
||||
});
|
||||
|
||||
AppSettings copyWith({
|
||||
String? suffix,
|
||||
bool? continuousMode,
|
||||
bool? vibrate,
|
||||
bool? sound,
|
||||
}) {
|
||||
return AppSettings(
|
||||
suffix: suffix ?? this.suffix,
|
||||
continuousMode: continuousMode ?? this.continuousMode,
|
||||
vibrate: vibrate ?? this.vibrate,
|
||||
sound: sound ?? this.sound,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [suffix, continuousMode, vibrate, sound];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import '../entities/app_settings.dart';
|
||||
|
||||
abstract class SettingsRepository {
|
||||
Future<AppSettings> loadSettings();
|
||||
Future<void> saveSuffix(String suffix);
|
||||
Future<void> saveContinuousMode(bool enabled);
|
||||
Future<void> saveFeedbackToggles({required bool vibrate, required bool sound});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../domain/repositories/settings_repository.dart';
|
||||
import 'settings_state.dart';
|
||||
|
||||
class SettingsCubit extends Cubit<SettingsState> {
|
||||
final SettingsRepository _settingsRepository;
|
||||
|
||||
SettingsCubit(this._settingsRepository) : super(const SettingsState());
|
||||
|
||||
Future<void> loadSettings() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
final settings = await _settingsRepository.loadSettings();
|
||||
emit(state.copyWith(settings: settings, isLoading: false));
|
||||
} catch (_) {
|
||||
emit(state.copyWith(isLoading: false));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateSuffix(String suffix) async {
|
||||
final updated = state.settings.copyWith(suffix: suffix);
|
||||
emit(state.copyWith(settings: updated));
|
||||
await _settingsRepository.saveSuffix(suffix);
|
||||
}
|
||||
|
||||
Future<void> updateContinuousMode(bool enabled) async {
|
||||
final updated = state.settings.copyWith(continuousMode: enabled);
|
||||
emit(state.copyWith(settings: updated));
|
||||
await _settingsRepository.saveContinuousMode(enabled);
|
||||
}
|
||||
|
||||
Future<void> updateFeedback({bool? vibrate, bool? sound}) async {
|
||||
final updated = state.settings.copyWith(
|
||||
vibrate: vibrate ?? state.settings.vibrate,
|
||||
sound: sound ?? state.settings.sound,
|
||||
);
|
||||
emit(state.copyWith(settings: updated));
|
||||
await _settingsRepository.saveFeedbackToggles(
|
||||
vibrate: updated.vibrate,
|
||||
sound: updated.sound,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../domain/entities/app_settings.dart';
|
||||
|
||||
class SettingsState extends Equatable {
|
||||
final AppSettings settings;
|
||||
final bool isLoading;
|
||||
|
||||
const SettingsState({
|
||||
this.settings = const AppSettings(),
|
||||
this.isLoading = false,
|
||||
});
|
||||
|
||||
SettingsState copyWith({
|
||||
AppSettings? settings,
|
||||
bool? isLoading,
|
||||
}) {
|
||||
return SettingsState(
|
||||
settings: settings ?? this.settings,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [settings, isLoading];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/constants/app_constants.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../../connection/presentation/cubit/connection_cubit.dart';
|
||||
import '../../../connection/presentation/cubit/connection_state.dart';
|
||||
import '../../../connection/presentation/screens/connect_screen.dart';
|
||||
import '../cubit/settings_cubit.dart';
|
||||
import '../cubit/settings_state.dart';
|
||||
|
||||
class SettingsScreen extends StatelessWidget {
|
||||
const SettingsScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Impostazioni'),
|
||||
),
|
||||
body: BlocBuilder<SettingsCubit, SettingsState>(
|
||||
builder: (context, settingsState) {
|
||||
final settings = settingsState.settings;
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
children: [
|
||||
// PC Connection Section
|
||||
const _SectionHeader(title: 'CONNESSIONE PC'),
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
BlocBuilder<ConnectionCubit, ServerConnectionState>(
|
||||
builder: (context, connState) {
|
||||
final isConnected = connState.isConnected;
|
||||
return ListTile(
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: (isConnected ? AppTheme.success : AppTheme.darkTextSecondary)
|
||||
.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.computer_rounded,
|
||||
color: isConnected ? AppTheme.success : AppTheme.darkTextSecondary,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
title: const Text('Server PC'),
|
||||
subtitle: Text(
|
||||
isConnected
|
||||
? 'Connesso a ${connState.info.displayName}'
|
||||
: (connState.info.isConfigured
|
||||
? 'Non connesso (${connState.info.ip})'
|
||||
: 'Nessun PC configurato'),
|
||||
style: const TextStyle(fontSize: 13),
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right_rounded),
|
||||
onTap: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const ConnectScreen()),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
const Divider(height: 1),
|
||||
ListTile(
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.send_rounded, color: AppTheme.primary, size: 22),
|
||||
),
|
||||
title: const Text('Invia Test di Digitazione'),
|
||||
subtitle: const Text(
|
||||
'Digita "TEST-CATELLI-123" sul PC attivo',
|
||||
style: TextStyle(fontSize: 13),
|
||||
),
|
||||
onTap: () {
|
||||
context.read<ConnectionCubit>().sendCode(
|
||||
code: 'TEST-CATELLI-123',
|
||||
suffix: settings.suffix,
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Test di digitazione inviato al PC!'),
|
||||
duration: Duration(seconds: 1),
|
||||
backgroundColor: AppTheme.darkCard,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Keyboard Emulation Section
|
||||
const _SectionHeader(title: 'EMULAZIONE TASTIERA PC'),
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
_RadioOption(
|
||||
title: 'Tasto Invio (Enter)',
|
||||
subtitle: 'Preme Invio dopo ogni codice (consigliato per Excel, ERP, gestionali)',
|
||||
isSelected: settings.suffix == AppConstants.suffixEnter,
|
||||
onTap: () {
|
||||
context.read<SettingsCubit>().updateSuffix(AppConstants.suffixEnter);
|
||||
},
|
||||
),
|
||||
const Divider(height: 1),
|
||||
_RadioOption(
|
||||
title: 'Tasto Tabulatore (Tab)',
|
||||
subtitle: 'Sposta il cursore al campo/cella successiva',
|
||||
isSelected: settings.suffix == AppConstants.suffixTab,
|
||||
onTap: () {
|
||||
context.read<SettingsCubit>().updateSuffix(AppConstants.suffixTab);
|
||||
},
|
||||
),
|
||||
const Divider(height: 1),
|
||||
_RadioOption(
|
||||
title: 'Nessun tasto finale',
|
||||
subtitle: 'Scrive solo la stringa pura del codice a barre',
|
||||
isSelected: settings.suffix == AppConstants.suffixNone,
|
||||
onTap: () {
|
||||
context.read<SettingsCubit>().updateSuffix(AppConstants.suffixNone);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Scan & Feedback Section
|
||||
const _SectionHeader(title: 'SCANSIONE E FEEDBACK'),
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
SwitchListTile(
|
||||
secondary: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.repeat_rounded, color: AppTheme.primary, size: 22),
|
||||
),
|
||||
title: const Text('Scansione Continua'),
|
||||
subtitle: const Text(
|
||||
'Continua a leggere codici in sequenza senza pause',
|
||||
style: TextStyle(fontSize: 13),
|
||||
),
|
||||
value: settings.continuousMode,
|
||||
onChanged: (val) {
|
||||
context.read<SettingsCubit>().updateContinuousMode(val);
|
||||
},
|
||||
),
|
||||
const Divider(height: 1),
|
||||
SwitchListTile(
|
||||
secondary: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.vibration_rounded, color: AppTheme.primary, size: 22),
|
||||
),
|
||||
title: const Text('Vibrazione alla lettura'),
|
||||
subtitle: const Text(
|
||||
'Feedback aptico alla decodifica del codice',
|
||||
style: TextStyle(fontSize: 13),
|
||||
),
|
||||
value: settings.vibrate,
|
||||
onChanged: (val) {
|
||||
context.read<SettingsCubit>().updateFeedback(vibrate: val);
|
||||
},
|
||||
),
|
||||
const Divider(height: 1),
|
||||
SwitchListTile(
|
||||
secondary: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.volume_up_rounded, color: AppTheme.primary, size: 22),
|
||||
),
|
||||
title: const Text('Suono di conferma'),
|
||||
subtitle: const Text(
|
||||
'Segnale acustico alla lettura del barcode',
|
||||
style: TextStyle(fontSize: 13),
|
||||
),
|
||||
value: settings.sound,
|
||||
onChanged: (val) {
|
||||
context.read<SettingsCubit>().updateFeedback(sound: val);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Info Section
|
||||
const _SectionHeader(title: 'INFORMAZIONI'),
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.business_rounded, color: AppTheme.primary, size: 22),
|
||||
),
|
||||
title: const Text('Organizzazione'),
|
||||
subtitle: const Text(AppConstants.organization, style: TextStyle(fontSize: 13)),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
ListTile(
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.info_outline_rounded, color: AppTheme.primary, size: 22),
|
||||
),
|
||||
title: const Text('Versione App'),
|
||||
subtitle: const Text(
|
||||
'${AppConstants.appVersion} (Flutter Clean Architecture & Cubit)',
|
||||
style: TextStyle(fontSize: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RadioOption extends StatelessWidget {
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final bool isSelected;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _RadioOption({
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.isSelected,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
margin: const EdgeInsets.only(top: 2),
|
||||
width: 20,
|
||||
height: 20,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: isSelected ? AppTheme.primary : AppTheme.darkBorder,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
child: isSelected
|
||||
? Center(
|
||||
child: Container(
|
||||
width: 10,
|
||||
height: 10,
|
||||
decoration: const BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: AppTheme.primary,
|
||||
),
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isSelected ? AppTheme.darkTextPrimary : AppTheme.darkTextSecondary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
subtitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
color: AppTheme.darkTextSecondary,
|
||||
height: 1.3,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionHeader extends StatelessWidget {
|
||||
final String title;
|
||||
|
||||
const _SectionHeader({required this.title});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 4, bottom: 8),
|
||||
child: Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppTheme.secondary,
|
||||
letterSpacing: 1.1,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+87
-29
@@ -1,8 +1,27 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'screens/scanner_screen.dart';
|
||||
import 'services/connection_service.dart';
|
||||
import 'core/services/feedback_service.dart';
|
||||
import 'core/theme/app_theme.dart';
|
||||
import 'features/connection/data/datasources/connection_local_datasource.dart';
|
||||
import 'features/connection/data/datasources/connection_remote_datasource.dart';
|
||||
import 'features/connection/data/datasources/udp_discovery_datasource.dart';
|
||||
import 'features/connection/data/repositories/connection_repository_impl.dart';
|
||||
import 'features/connection/domain/repositories/connection_repository.dart';
|
||||
import 'features/connection/presentation/cubit/connection_cubit.dart';
|
||||
import 'features/connection/presentation/cubit/discovery_cubit.dart';
|
||||
import 'features/scanner/data/datasources/scan_history_datasource.dart';
|
||||
import 'features/scanner/data/repositories/scan_repository_impl.dart';
|
||||
import 'features/scanner/domain/repositories/scan_repository.dart';
|
||||
import 'features/scanner/presentation/cubit/history_cubit.dart';
|
||||
import 'features/scanner/presentation/cubit/scanner_cubit.dart';
|
||||
import 'features/scanner/presentation/screens/scanner_screen.dart';
|
||||
import 'features/settings/data/datasources/settings_local_datasource.dart';
|
||||
import 'features/settings/data/repositories/settings_repository_impl.dart';
|
||||
import 'features/settings/domain/repositories/settings_repository.dart';
|
||||
import 'features/settings/presentation/cubit/settings_cubit.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
@@ -13,44 +32,83 @@ void main() async {
|
||||
DeviceOrientation.portraitDown,
|
||||
]);
|
||||
|
||||
final connectionService = ConnectionService();
|
||||
await connectionService.initialize();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
runApp(BarcodeReaderApp(connectionService: connectionService));
|
||||
// Core services
|
||||
const feedbackService = FeedbackService();
|
||||
|
||||
// Repositories
|
||||
final SettingsRepository settingsRepository = SettingsRepositoryImpl(
|
||||
SettingsLocalDataSource(prefs),
|
||||
);
|
||||
|
||||
final ConnectionRepository connectionRepository = ConnectionRepositoryImpl(
|
||||
localDataSource: ConnectionLocalDataSource(prefs),
|
||||
remoteDataSource: ConnectionRemoteDataSource(),
|
||||
discoveryDataSource: const UdpDiscoveryDataSource(),
|
||||
);
|
||||
|
||||
final ScanRepository scanRepository = ScanRepositoryImpl(
|
||||
ScanHistoryDataSource(prefs),
|
||||
);
|
||||
|
||||
runApp(
|
||||
BarcodeReaderApp(
|
||||
settingsRepository: settingsRepository,
|
||||
connectionRepository: connectionRepository,
|
||||
scanRepository: scanRepository,
|
||||
feedbackService: feedbackService,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class BarcodeReaderApp extends StatelessWidget {
|
||||
final ConnectionService connectionService;
|
||||
final SettingsRepository settingsRepository;
|
||||
final ConnectionRepository connectionRepository;
|
||||
final ScanRepository scanRepository;
|
||||
final FeedbackService feedbackService;
|
||||
|
||||
const BarcodeReaderApp({super.key, required this.connectionService});
|
||||
const BarcodeReaderApp({
|
||||
super.key,
|
||||
required this.settingsRepository,
|
||||
required this.connectionRepository,
|
||||
required this.scanRepository,
|
||||
required this.feedbackService,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const primaryColor = Color(0xFF0284C7); // Sky blue / corporate cyan
|
||||
|
||||
return MaterialApp(
|
||||
title: 'Catelli Barcode Scanner',
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider<SettingsCubit>(
|
||||
create: (_) => SettingsCubit(settingsRepository)..loadSettings(),
|
||||
),
|
||||
BlocProvider<ConnectionCubit>(
|
||||
create: (_) => ConnectionCubit(connectionRepository)..initialize(),
|
||||
),
|
||||
BlocProvider<DiscoveryCubit>(
|
||||
create: (_) => DiscoveryCubit(connectionRepository),
|
||||
),
|
||||
BlocProvider<HistoryCubit>(
|
||||
create: (_) => HistoryCubit(scanRepository)..loadHistory(),
|
||||
),
|
||||
BlocProvider<ScannerCubit>(
|
||||
create: (context) => ScannerCubit(
|
||||
connectionCubit: context.read<ConnectionCubit>(),
|
||||
settingsCubit: context.read<SettingsCubit>(),
|
||||
historyCubit: context.read<HistoryCubit>(),
|
||||
feedbackService: feedbackService,
|
||||
),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
title: 'Catelli Barcode Reader',
|
||||
debugShowCheckedModeBanner: false,
|
||||
themeMode: ThemeMode.dark, // Dark theme provides optimal contrast for scanner viewfinder
|
||||
theme: ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.light,
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: primaryColor,
|
||||
brightness: Brightness.light,
|
||||
theme: AppTheme.lightTheme,
|
||||
darkTheme: AppTheme.darkTheme,
|
||||
home: const ScannerScreen(),
|
||||
),
|
||||
),
|
||||
darkTheme: ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.dark,
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: primaryColor,
|
||||
brightness: Brightness.dark,
|
||||
surface: const Color(0xFF0F172A),
|
||||
),
|
||||
scaffoldBackgroundColor: const Color(0xFF020617),
|
||||
),
|
||||
home: ScannerScreen(connectionService: connectionService),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
|
||||
import '../services/connection_service.dart';
|
||||
import '../services/discovery_service.dart';
|
||||
|
||||
class ConnectScreen extends StatefulWidget {
|
||||
final ConnectionService connectionService;
|
||||
|
||||
const ConnectScreen({super.key, required this.connectionService});
|
||||
|
||||
@override
|
||||
State<ConnectScreen> createState() => _ConnectScreenState();
|
||||
}
|
||||
|
||||
class _ConnectScreenState extends State<ConnectScreen> {
|
||||
late TextEditingController _ipController;
|
||||
late TextEditingController _portController;
|
||||
late TextEditingController _pinController;
|
||||
|
||||
bool _isSearching = false;
|
||||
List<DiscoveredServer> _discoveredServers = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_ipController = TextEditingController(text: widget.connectionService.ip);
|
||||
_portController = TextEditingController(text: widget.connectionService.port.toString());
|
||||
_pinController = TextEditingController(text: widget.connectionService.pin);
|
||||
|
||||
// Avvia automaticamente una ricerca rapida su Wi-Fi all'apertura della schermata
|
||||
_searchWifiServers();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ipController.dispose();
|
||||
_portController.dispose();
|
||||
_pinController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _searchWifiServers() async {
|
||||
setState(() {
|
||||
_isSearching = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final results = await DiscoveryService.discover(timeout: const Duration(seconds: 2));
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_discoveredServers = results;
|
||||
_isSearching = false;
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isSearching = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _scanServerQrCode() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (ctx) {
|
||||
return SizedBox(
|
||||
height: MediaQuery.of(ctx).size.height * 0.7,
|
||||
child: Column(
|
||||
children: [
|
||||
AppBar(
|
||||
title: const Text('Inquadra QR del PC'),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: MobileScanner(
|
||||
onDetect: (capture) {
|
||||
final barcode = capture.barcodes.firstOrNull;
|
||||
if (barcode?.rawValue == null) return;
|
||||
final val = barcode!.rawValue!;
|
||||
|
||||
try {
|
||||
// Prova a parsare come JSON pairing
|
||||
final json = jsonDecode(val) as Map<String, dynamic>;
|
||||
final ip = json['ip'] as String?;
|
||||
final port = json['port'] as int? ?? 8765;
|
||||
final pin = json['pin'] as String? ?? '';
|
||||
final name = json['name'] as String? ?? 'PC Server';
|
||||
|
||||
if (ip != null && ip.isNotEmpty) {
|
||||
Navigator.pop(ctx);
|
||||
_applyAndConnect(ip, port, pin, name);
|
||||
return;
|
||||
}
|
||||
} catch (_) {
|
||||
// Se è un URL come ws://192.168.1.50:8765/ws
|
||||
final uri = Uri.tryParse(val);
|
||||
if (uri != null && uri.host.isNotEmpty) {
|
||||
Navigator.pop(ctx);
|
||||
_applyAndConnect(uri.host, uri.port != 0 ? uri.port : 8765, '', 'PC');
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _applyAndConnect(String ip, int port, String pin, String? name) {
|
||||
widget.connectionService.setServer(
|
||||
ip: ip,
|
||||
port: port,
|
||||
pin: pin,
|
||||
serverName: name,
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Connessione a $ip:$port...'),
|
||||
backgroundColor: Colors.blueAccent,
|
||||
),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
void _onManualConnect() {
|
||||
final ip = _ipController.text.trim();
|
||||
final port = int.tryParse(_portController.text.trim()) ?? 8765;
|
||||
final pin = _pinController.text.trim();
|
||||
|
||||
if (ip.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Inserisci un indirizzo IP valido.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
_applyAndConnect(ip, port, pin, null);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final status = widget.connectionService.status;
|
||||
final isConnected = status == ConnectionStatus.connected;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Connessione al PC'),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
// Stato attuale
|
||||
Card(
|
||||
color: isConnected
|
||||
? Colors.green.withValues(alpha: 0.15)
|
||||
: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isConnected ? Icons.check_circle : Icons.portable_wifi_off,
|
||||
color: isConnected ? Colors.green : Colors.grey,
|
||||
size: 32,
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
isConnected ? 'Connesso' : 'Non Connesso',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isConnected ? Colors.green : null,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
widget.connectionService.statusMessage,
|
||||
style: const TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (isConnected)
|
||||
TextButton(
|
||||
onPressed: () => widget.connectionService.disconnect(),
|
||||
child: const Text('Disconnetti'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Metodo 1: Inquadra QR
|
||||
FilledButton.icon(
|
||||
style: FilledButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
icon: const Icon(Icons.qr_code_scanner, size: 24),
|
||||
label: const Text('Inquadra QR Code sul PC', style: TextStyle(fontSize: 16)),
|
||||
onPressed: _scanServerQrCode,
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Metodo 2: Rilevamento automatico su Wi-Fi
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
const Text(
|
||||
'PC Rilevati sulla Rete Wi-Fi',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
IconButton(
|
||||
icon: _isSearching
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh),
|
||||
tooltip: 'Aggiorna ricerca Wi-Fi',
|
||||
onPressed: _isSearching ? null : _searchWifiServers,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
|
||||
if (_discoveredServers.isEmpty)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.grey.withValues(alpha: 0.3)),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
_isSearching
|
||||
? 'Ricerca PC in corso sulla rete locale...'
|
||||
: 'Nessun PC rilevato automaticamente. Assicurati che il server sia avviato e collegato allo stesso Wi-Fi, oppure inquadra il QR code.',
|
||||
style: const TextStyle(color: Colors.grey, fontSize: 13),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
)
|
||||
else
|
||||
..._discoveredServers.map((srv) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
child: ListTile(
|
||||
leading: const CircleAvatar(
|
||||
child: Icon(Icons.computer),
|
||||
),
|
||||
title: Text(srv.serverName, style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
subtitle: Text('${srv.ip}:${srv.port} ${srv.pinRequired ? "• Richiede PIN" : ""}'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
_applyAndConnect(srv.ip, srv.port, '', srv.serverName);
|
||||
},
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// Metodo 3: Configurazione manuale
|
||||
const Text(
|
||||
'Configurazione Manuale',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextField(
|
||||
controller: _ipController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Indirizzo IP del PC',
|
||||
hintText: 'Es. 192.168.1.50',
|
||||
prefixIcon: Icon(Icons.lan),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: TextInputType.url,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: TextField(
|
||||
controller: _portController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Porta',
|
||||
hintText: '8765',
|
||||
prefixIcon: Icon(Icons.tag),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: TextField(
|
||||
controller: _pinController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'PIN (opzionale)',
|
||||
hintText: 'Codice di sicurezza',
|
||||
prefixIcon: Icon(Icons.lock_outline),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
obscureText: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
icon: const Icon(Icons.save),
|
||||
label: const Text('Salva e Connetti Manualmente'),
|
||||
onPressed: _onManualConnect,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../services/connection_service.dart';
|
||||
|
||||
class HistoryScreen extends StatefulWidget {
|
||||
final ConnectionService connectionService;
|
||||
|
||||
const HistoryScreen({super.key, required this.connectionService});
|
||||
|
||||
@override
|
||||
State<HistoryScreen> createState() => _HistoryScreenState();
|
||||
}
|
||||
|
||||
class _HistoryScreenState extends State<HistoryScreen> {
|
||||
String _searchQuery = '';
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _confirmClear() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Cancellare Cronologia?'),
|
||||
content: const Text('Tutte le scansioni salvate sul dispositivo verranno eliminate definitivamente.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: Colors.red),
|
||||
onPressed: () {
|
||||
widget.connectionService.clearHistory();
|
||||
Navigator.pop(ctx);
|
||||
},
|
||||
child: const Text('Cancella Tutto'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: widget.connectionService,
|
||||
builder: (context, _) {
|
||||
final allHistory = widget.connectionService.history;
|
||||
final filtered = _searchQuery.isEmpty
|
||||
? allHistory
|
||||
: allHistory.where((item) => item.code.toLowerCase().contains(_searchQuery.toLowerCase())).toList();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Cronologia Scansioni'),
|
||||
actions: [
|
||||
if (allHistory.isNotEmpty)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
tooltip: 'Cancella cronologia',
|
||||
onPressed: _confirmClear,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
if (allHistory.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: TextField(
|
||||
controller: _searchController,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Cerca tra i codici...',
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: _searchQuery.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.clear),
|
||||
onPressed: () {
|
||||
_searchController.clear();
|
||||
setState(() {
|
||||
_searchQuery = '';
|
||||
});
|
||||
},
|
||||
)
|
||||
: null,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
onChanged: (val) {
|
||||
setState(() {
|
||||
_searchQuery = val.trim();
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: filtered.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
_searchQuery.isEmpty ? Icons.history_toggle_off : Icons.search_off,
|
||||
size: 64,
|
||||
color: Colors.grey.shade400,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
_searchQuery.isEmpty
|
||||
? 'Nessuna scansione presente'
|
||||
: 'Nessun risultato trovato per "$_searchQuery"',
|
||||
style: const TextStyle(color: Colors.grey, fontSize: 16),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.separated(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: filtered.length,
|
||||
separatorBuilder: (context, index) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, index) {
|
||||
final item = filtered[index];
|
||||
return Card(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: item.sentSuccessfully
|
||||
? Colors.green.withValues(alpha: 0.15)
|
||||
: Colors.orange.withValues(alpha: 0.15),
|
||||
child: Icon(
|
||||
item.sentSuccessfully ? Icons.check : Icons.warning_amber,
|
||||
color: item.sentSuccessfully ? Colors.green : Colors.orange,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
title: SelectableText(
|
||||
item.code,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${item.format} • ${item.timestamp.hour.toString().padLeft(2, '0')}:${item.timestamp.minute.toString().padLeft(2, '0')}:${item.timestamp.second.toString().padLeft(2, '0')} - ${item.timestamp.day}/${item.timestamp.month}/${item.timestamp.year}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.grey),
|
||||
),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy, size: 20),
|
||||
tooltip: 'Copia codice',
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: item.code));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Copiato negli appunti'),
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.send, size: 20),
|
||||
tooltip: 'Invia di nuovo al PC',
|
||||
onPressed: () {
|
||||
widget.connectionService.sendCode(item.code, format: item.format);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Inviato "${item.code}" al PC'),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,443 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
|
||||
import '../services/connection_service.dart';
|
||||
import '../widgets/scanner_overlay.dart';
|
||||
import 'connect_screen.dart';
|
||||
import 'history_screen.dart';
|
||||
import 'settings_screen.dart';
|
||||
|
||||
class ScannerScreen extends StatefulWidget {
|
||||
final ConnectionService connectionService;
|
||||
|
||||
const ScannerScreen({super.key, required this.connectionService});
|
||||
|
||||
@override
|
||||
State<ScannerScreen> createState() => _ScannerScreenState();
|
||||
}
|
||||
|
||||
class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserver {
|
||||
late MobileScannerController _scannerController;
|
||||
bool _isTorchOn = false;
|
||||
String? _lastScannedValue;
|
||||
DateTime _lastScannedTime = DateTime.now().subtract(const Duration(seconds: 10));
|
||||
bool _isProcessing = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_scannerController = MobileScannerController(
|
||||
detectionSpeed: DetectionSpeed.normal,
|
||||
facing: CameraFacing.back,
|
||||
torchEnabled: false,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_scannerController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (!_scannerController.value.isInitialized) return;
|
||||
if (state == AppLifecycleState.inactive || state == AppLifecycleState.paused) {
|
||||
_scannerController.stop();
|
||||
} else if (state == AppLifecycleState.resumed) {
|
||||
_scannerController.start();
|
||||
}
|
||||
}
|
||||
|
||||
void _onDetect(BarcodeCapture capture) async {
|
||||
final barcodes = capture.barcodes;
|
||||
if (barcodes.isEmpty) return;
|
||||
|
||||
final first = barcodes.first;
|
||||
final rawValue = first.rawValue ?? first.displayValue;
|
||||
if (rawValue == null || rawValue.trim().isEmpty) return;
|
||||
|
||||
final now = DateTime.now();
|
||||
final isSameCode = rawValue == _lastScannedValue;
|
||||
final durationSinceLast = now.difference(_lastScannedTime);
|
||||
|
||||
// Debounce: se è lo stesso codice, aspetta almeno 1.5s (o 1.0s in continuo); se codice diverso, aspetta 600ms
|
||||
final minInterval = isSameCode
|
||||
? (widget.connectionService.continuousMode ? const Duration(milliseconds: 1000) : const Duration(milliseconds: 1800))
|
||||
: const Duration(milliseconds: 600);
|
||||
|
||||
if (durationSinceLast < minInterval || _isProcessing) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isProcessing = true;
|
||||
_lastScannedValue = rawValue;
|
||||
_lastScannedTime = now;
|
||||
|
||||
final formatName = first.format.name.replaceAll('BarcodeFormat.', '');
|
||||
await widget.connectionService.sendCode(rawValue, format: formatName);
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isProcessing = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _showManualInputDialog() {
|
||||
final textController = TextEditingController();
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Row(
|
||||
children: [
|
||||
Icon(Icons.keyboard_outlined),
|
||||
SizedBox(width: 8),
|
||||
Text('Digitazione Manuale'),
|
||||
],
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Digita o incolla il codice da inviare direttamente al PC:',
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: textController,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Es. 8001234567890 o ABC-123',
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.paste),
|
||||
tooltip: 'Incolla dagli appunti',
|
||||
onPressed: () async {
|
||||
final data = await Clipboard.getData('text/plain');
|
||||
if (data?.text != null) {
|
||||
textController.text = data!.text!;
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
onSubmitted: (val) {
|
||||
if (val.trim().isNotEmpty) {
|
||||
widget.connectionService.sendCode(val.trim(), format: 'Manuale');
|
||||
Navigator.pop(ctx);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Annulla'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
icon: const Icon(Icons.send),
|
||||
label: const Text('Invia al PC'),
|
||||
onPressed: () {
|
||||
final val = textController.text.trim();
|
||||
if (val.isNotEmpty) {
|
||||
widget.connectionService.sendCode(val, format: 'Manuale');
|
||||
Navigator.pop(ctx);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusPill() {
|
||||
final status = widget.connectionService.status;
|
||||
Color color;
|
||||
IconData icon;
|
||||
String text;
|
||||
|
||||
switch (status) {
|
||||
case ConnectionStatus.connected:
|
||||
color = Colors.greenAccent.shade700;
|
||||
icon = Icons.check_circle;
|
||||
text = widget.connectionService.serverName;
|
||||
break;
|
||||
case ConnectionStatus.connecting:
|
||||
color = Colors.orange;
|
||||
icon = Icons.sync;
|
||||
text = 'Connessione...';
|
||||
break;
|
||||
case ConnectionStatus.error:
|
||||
case ConnectionStatus.disconnected:
|
||||
color = Colors.redAccent;
|
||||
icon = Icons.error_outline;
|
||||
text = 'Disconnesso';
|
||||
break;
|
||||
}
|
||||
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ConnectScreen(connectionService: widget.connectionService),
|
||||
),
|
||||
);
|
||||
},
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.65),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: color, width: 1.5),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, color: color, size: 16),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: widget.connectionService,
|
||||
builder: (context, _) {
|
||||
final lastScan = widget.connectionService.lastScan;
|
||||
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
// Vista Fotocamera con MobileScanner
|
||||
MobileScanner(
|
||||
controller: _scannerController,
|
||||
onDetect: _onDetect,
|
||||
),
|
||||
|
||||
// Mirino centrale per allineamento codice
|
||||
const ScannerOverlay(),
|
||||
|
||||
// Barra superiore: Status pill, Flash, Cambio camera, Impostazioni
|
||||
SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
_buildStatusPill(),
|
||||
Row(
|
||||
children: [
|
||||
IconButton.filledTonal(
|
||||
icon: Icon(_isTorchOn ? Icons.flash_on : Icons.flash_off),
|
||||
onPressed: () async {
|
||||
await _scannerController.toggleTorch();
|
||||
setState(() {
|
||||
_isTorchOn = !_isTorchOn;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton.filledTonal(
|
||||
icon: const Icon(Icons.cameraswitch),
|
||||
onPressed: () => _scannerController.switchCamera(),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton.filledTonal(
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: 'Cronologia',
|
||||
onPressed: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => HistoryScreen(connectionService: widget.connectionService),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton.filledTonal(
|
||||
icon: const Icon(Icons.settings),
|
||||
tooltip: 'Impostazioni',
|
||||
onPressed: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => SettingsScreen(connectionService: widget.connectionService),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Controlli rapidi sotto la barra superiore: Modalità continuo & Suffisso rapido
|
||||
Positioned(
|
||||
top: 100,
|
||||
left: 16,
|
||||
right: 16,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// Pillola modalità continua
|
||||
ActionChip(
|
||||
avatar: Icon(
|
||||
widget.connectionService.continuousMode ? Icons.repeat_one : Icons.looks_one,
|
||||
size: 16,
|
||||
),
|
||||
label: Text(
|
||||
widget.connectionService.continuousMode ? 'Scansione Continua' : 'Scansione Singola',
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
backgroundColor: widget.connectionService.continuousMode
|
||||
? Theme.of(context).colorScheme.primaryContainer
|
||||
: Colors.black54,
|
||||
onPressed: () {
|
||||
widget.connectionService.setContinuousMode(!widget.connectionService.continuousMode);
|
||||
},
|
||||
),
|
||||
|
||||
// Suffisso tasto rapido (Enter / Tab / Nessuno)
|
||||
PopupMenuButton<String>(
|
||||
initialValue: widget.connectionService.suffix,
|
||||
tooltip: 'Cambia tasto finale',
|
||||
onSelected: (val) => widget.connectionService.setSuffix(val),
|
||||
itemBuilder: (context) => [
|
||||
const PopupMenuItem(value: 'enter', child: Text('Invio (Enter)')),
|
||||
const PopupMenuItem(value: 'tab', child: Text('Tabulatore (Tab)')),
|
||||
const PopupMenuItem(value: 'none', child: Text('Nessun tasto')),
|
||||
],
|
||||
child: Chip(
|
||||
avatar: const Icon(Icons.keyboard_return, size: 14),
|
||||
label: Text(
|
||||
widget.connectionService.suffix.toUpperCase(),
|
||||
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold),
|
||||
),
|
||||
backgroundColor: Colors.black54,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Floating Action Button per digitazione manuale
|
||||
Positioned(
|
||||
bottom: lastScan != null ? 150 : 32,
|
||||
right: 16,
|
||||
child: FloatingActionButton.extended(
|
||||
heroTag: 'manual_input',
|
||||
icon: const Icon(Icons.keyboard),
|
||||
label: const Text('Manuale'),
|
||||
onPressed: _showManualInputDialog,
|
||||
),
|
||||
),
|
||||
|
||||
// Scheda inferiore: Ultimo codice scansionato
|
||||
if (lastScan != null)
|
||||
Positioned(
|
||||
left: 16,
|
||||
right: 16,
|
||||
bottom: 24,
|
||||
child: Card(
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.95),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
lastScan.sentSuccessfully ? Icons.check_circle : Icons.warning_amber_rounded,
|
||||
color: lastScan.sentSuccessfully ? Colors.green : Colors.orange,
|
||||
size: 28,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
lastScan.format,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
'${lastScan.timestamp.hour.toString().padLeft(2, '0')}:${lastScan.timestamp.minute.toString().padLeft(2, '0')}:${lastScan.timestamp.second.toString().padLeft(2, '0')}',
|
||||
style: const TextStyle(fontSize: 11, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
lastScan.code,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy, size: 20),
|
||||
tooltip: 'Copia',
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: lastScan.code));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Codice copiato negli appunti'),
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.replay, size: 20),
|
||||
tooltip: 'Invia di nuovo al PC',
|
||||
onPressed: () {
|
||||
widget.connectionService.sendCode(lastScan.code, format: lastScan.format);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../services/connection_service.dart';
|
||||
import 'connect_screen.dart';
|
||||
|
||||
class SettingsScreen extends StatelessWidget {
|
||||
final ConnectionService connectionService;
|
||||
|
||||
const SettingsScreen({super.key, required this.connectionService});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: connectionService,
|
||||
builder: (context, _) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Impostazioni'),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
children: [
|
||||
// Sezione Connessione PC
|
||||
const _SectionHeader(title: 'CONNESSIONE PC'),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.computer),
|
||||
title: const Text('Stato Server PC'),
|
||||
subtitle: Text(
|
||||
connectionService.isConnected
|
||||
? 'Connesso a ${connectionService.serverName} (${connectionService.ip}:${connectionService.port})'
|
||||
: 'Non connesso (${connectionService.ip.isNotEmpty ? connectionService.ip : "Nessun IP"})',
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ConnectScreen(connectionService: connectionService),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.send),
|
||||
title: const Text('Invia Test di Digitazione'),
|
||||
subtitle: const Text('Digita "TEST-CATELLI-123" sul PC per verificare'),
|
||||
onTap: () {
|
||||
connectionService.sendCode('TEST-CATELLI-123', format: 'Test');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Test di digitazione inviato al PC!'),
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
const Divider(),
|
||||
|
||||
// Sezione Comportamento Tastiera
|
||||
const _SectionHeader(title: 'EMULAZIONE TASTIERA PC'),
|
||||
RadioGroup<String>(
|
||||
groupValue: connectionService.suffix,
|
||||
onChanged: (val) {
|
||||
if (val != null) connectionService.setSuffix(val);
|
||||
},
|
||||
child: Column(
|
||||
children: const [
|
||||
RadioListTile<String>(
|
||||
title: Text('Tasto Invio (Enter)'),
|
||||
subtitle: Text('Preme Invio dopo ogni scansione (consigliato per Excel, gestionale, ERP)'),
|
||||
value: 'enter',
|
||||
),
|
||||
RadioListTile<String>(
|
||||
title: Text('Tasto Tabulatore (Tab)'),
|
||||
subtitle: Text('Sposta il cursore alla cella/campo successivo'),
|
||||
value: 'tab',
|
||||
),
|
||||
RadioListTile<String>(
|
||||
title: Text('Nessun tasto finale'),
|
||||
subtitle: Text('Scrive unicamente la stringa del codice a barre'),
|
||||
value: 'none',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const Divider(),
|
||||
|
||||
// Sezione Scanner & Feedback
|
||||
const _SectionHeader(title: 'SCANSIONE E FEEDBACK'),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.repeat),
|
||||
title: const Text('Scansione Continua'),
|
||||
subtitle: const Text('Continua a scansionare codici senza dover ripremere'),
|
||||
value: connectionService.continuousMode,
|
||||
onChanged: (val) => connectionService.setContinuousMode(val),
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.vibration),
|
||||
title: const Text('Vibrazione alla lettura'),
|
||||
subtitle: const Text('Feedback aptico alla lettura del barcode'),
|
||||
value: connectionService.vibrate,
|
||||
onChanged: (val) => connectionService.setFeedbackToggles(
|
||||
vibrate: val,
|
||||
sound: connectionService.sound,
|
||||
),
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.volume_up),
|
||||
title: const Text('Suono acustico alla lettura'),
|
||||
subtitle: const Text('Riproduce il "beep" di sistema a ogni scansione'),
|
||||
value: connectionService.sound,
|
||||
onChanged: (val) => connectionService.setFeedbackToggles(
|
||||
vibrate: connectionService.vibrate,
|
||||
sound: val,
|
||||
),
|
||||
),
|
||||
|
||||
const Divider(),
|
||||
|
||||
// Sezione Info
|
||||
const _SectionHeader(title: 'INFORMAZIONI'),
|
||||
const ListTile(
|
||||
leading: Icon(Icons.business),
|
||||
title: Text('Organizzazione'),
|
||||
subtitle: Text('Catelli Srl (com.catellisrl)'),
|
||||
),
|
||||
const ListTile(
|
||||
leading: Icon(Icons.info_outline),
|
||||
title: Text('Versione App'),
|
||||
subtitle: Text('1.0.0 (Release Cross-Platform)'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionHeader extends StatelessWidget {
|
||||
final String title;
|
||||
|
||||
const _SectionHeader({required this.title});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
letterSpacing: 1.1,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,338 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
|
||||
import '../models/scan_record.dart';
|
||||
import 'feedback_service.dart';
|
||||
import 'storage_service.dart';
|
||||
|
||||
enum ConnectionStatus {
|
||||
disconnected,
|
||||
connecting,
|
||||
connected,
|
||||
error,
|
||||
}
|
||||
|
||||
class ConnectionService extends ChangeNotifier {
|
||||
String _ip = '';
|
||||
int _port = 8765;
|
||||
String _pin = '';
|
||||
String _serverName = '';
|
||||
String _suffix = 'enter'; // enter, tab, none
|
||||
bool _continuousMode = false;
|
||||
bool _vibrate = true;
|
||||
bool _sound = true;
|
||||
|
||||
ConnectionStatus _status = ConnectionStatus.disconnected;
|
||||
String _statusMessage = 'Non connesso';
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription? _channelSub;
|
||||
Timer? _reconnectTimer;
|
||||
Timer? _pingTimer;
|
||||
bool _intentionalDisconnect = false;
|
||||
|
||||
List<ScanRecord> _history = [];
|
||||
ScanRecord? _lastScan;
|
||||
|
||||
String get ip => _ip;
|
||||
int get port => _port;
|
||||
String get pin => _pin;
|
||||
String get serverName => _serverName.isNotEmpty ? _serverName : (_ip.isNotEmpty ? _ip : 'Nessun PC');
|
||||
String get suffix => _suffix;
|
||||
bool get continuousMode => _continuousMode;
|
||||
bool get vibrate => _vibrate;
|
||||
bool get sound => _sound;
|
||||
ConnectionStatus get status => _status;
|
||||
String get statusMessage => _statusMessage;
|
||||
List<ScanRecord> get history => _history;
|
||||
ScanRecord? get lastScan => _lastScan;
|
||||
bool get isConnected => _status == ConnectionStatus.connected;
|
||||
|
||||
Future<void> initialize() async {
|
||||
final settings = await StorageService.loadSettings();
|
||||
_ip = settings['ip'] as String? ?? '';
|
||||
_port = settings['port'] as int? ?? 8765;
|
||||
_pin = settings['pin'] as String? ?? '';
|
||||
_serverName = settings['serverName'] as String? ?? '';
|
||||
_suffix = settings['suffix'] as String? ?? 'enter';
|
||||
_continuousMode = settings['continuous'] as bool? ?? false;
|
||||
_vibrate = settings['vibrate'] as bool? ?? true;
|
||||
_sound = settings['sound'] as bool? ?? true;
|
||||
|
||||
_history = await StorageService.loadHistory();
|
||||
if (_history.isNotEmpty) {
|
||||
_lastScan = _history.first;
|
||||
}
|
||||
notifyListeners();
|
||||
|
||||
if (_ip.isNotEmpty) {
|
||||
connect();
|
||||
}
|
||||
}
|
||||
|
||||
void setServer({
|
||||
required String ip,
|
||||
required int port,
|
||||
required String pin,
|
||||
String? serverName,
|
||||
}) {
|
||||
_ip = ip.trim();
|
||||
_port = port;
|
||||
_pin = pin.trim();
|
||||
if (serverName != null && serverName.isNotEmpty) {
|
||||
_serverName = serverName;
|
||||
}
|
||||
StorageService.saveServerConnection(
|
||||
ip: _ip,
|
||||
port: _port,
|
||||
pin: _pin,
|
||||
serverName: _serverName,
|
||||
);
|
||||
notifyListeners();
|
||||
connect();
|
||||
}
|
||||
|
||||
void setSuffix(String suffix) {
|
||||
_suffix = suffix;
|
||||
StorageService.saveSuffix(suffix);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setContinuousMode(bool enabled) {
|
||||
_continuousMode = enabled;
|
||||
StorageService.saveContinuousMode(enabled);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setFeedbackToggles({required bool vibrate, required bool sound}) {
|
||||
_vibrate = vibrate;
|
||||
_sound = sound;
|
||||
StorageService.saveFeedbackToggles(vibrate: vibrate, sound: sound);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> connect() async {
|
||||
if (_ip.isEmpty) {
|
||||
_status = ConnectionStatus.disconnected;
|
||||
_statusMessage = 'Indirizzo IP non impostato';
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
_intentionalDisconnect = false;
|
||||
_reconnectTimer?.cancel();
|
||||
_pingTimer?.cancel();
|
||||
_closeChannel();
|
||||
|
||||
_status = ConnectionStatus.connecting;
|
||||
_statusMessage = 'Connessione a $_ip:$_port in corso...';
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
final wsUrl = Uri.parse('ws://$_ip:$_port/ws');
|
||||
_channel = WebSocketChannel.connect(wsUrl);
|
||||
|
||||
// Timeout connection check via HTTP ping first or await channel stream
|
||||
_channelSub = _channel!.stream.listen(
|
||||
(data) {
|
||||
_handleIncomingMessage(data);
|
||||
},
|
||||
onError: (err) {
|
||||
_onConnectionError('Errore di connessione: $err');
|
||||
},
|
||||
onDone: () {
|
||||
_onConnectionClosed();
|
||||
},
|
||||
cancelOnError: true,
|
||||
);
|
||||
|
||||
// Handshake
|
||||
final deviceName = Platform.isAndroid ? 'Android' : (Platform.isIOS ? 'iPhone' : 'Dispositivo Mobile');
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'handshake',
|
||||
'device_name': deviceName,
|
||||
'pin': _pin,
|
||||
}));
|
||||
|
||||
_status = ConnectionStatus.connected;
|
||||
_statusMessage = 'Connesso a $_serverName ($_ip)';
|
||||
notifyListeners();
|
||||
|
||||
_startPingLoop();
|
||||
} catch (e) {
|
||||
_onConnectionError('Impossibile connettersi: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_intentionalDisconnect = true;
|
||||
_reconnectTimer?.cancel();
|
||||
_pingTimer?.cancel();
|
||||
_closeChannel();
|
||||
_status = ConnectionStatus.disconnected;
|
||||
_statusMessage = 'Disconnesso manualmente';
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _closeChannel() {
|
||||
_channelSub?.cancel();
|
||||
_channelSub = null;
|
||||
try {
|
||||
_channel?.sink.close();
|
||||
} catch (_) {}
|
||||
_channel = null;
|
||||
}
|
||||
|
||||
void _onConnectionError(String msg) {
|
||||
_status = ConnectionStatus.error;
|
||||
_statusMessage = msg;
|
||||
_closeChannel();
|
||||
notifyListeners();
|
||||
_scheduleReconnect();
|
||||
}
|
||||
|
||||
void _onConnectionClosed() {
|
||||
if (_intentionalDisconnect) {
|
||||
_status = ConnectionStatus.disconnected;
|
||||
_statusMessage = 'Disconnesso';
|
||||
} else {
|
||||
_status = ConnectionStatus.disconnected;
|
||||
_statusMessage = 'Connessione interrotta. Nuovo tentativo...';
|
||||
_scheduleReconnect();
|
||||
}
|
||||
_closeChannel();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _scheduleReconnect() {
|
||||
if (_intentionalDisconnect || _ip.isEmpty) return;
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = Timer(const Duration(seconds: 4), () {
|
||||
if (!_intentionalDisconnect && _status != ConnectionStatus.connected) {
|
||||
connect();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _startPingLoop() {
|
||||
_pingTimer?.cancel();
|
||||
_pingTimer = Timer.periodic(const Duration(seconds: 15), (t) {
|
||||
if (_status == ConnectionStatus.connected && _channel != null) {
|
||||
try {
|
||||
_channel!.sink.add(jsonEncode({'type': 'ping'}));
|
||||
} catch (_) {}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _handleIncomingMessage(dynamic raw) {
|
||||
try {
|
||||
final json = jsonDecode(raw.toString()) as Map<String, dynamic>;
|
||||
final type = json['type'] as String?;
|
||||
|
||||
if (type == 'welcome') {
|
||||
if (json['server_name'] != null) {
|
||||
_serverName = json['server_name'] as String;
|
||||
StorageService.saveServerConnection(ip: _ip, port: _port, pin: _pin, serverName: _serverName);
|
||||
}
|
||||
_status = ConnectionStatus.connected;
|
||||
_statusMessage = 'Connesso a $_serverName';
|
||||
notifyListeners();
|
||||
} else if (type == 'auth_error') {
|
||||
_status = ConnectionStatus.error;
|
||||
_statusMessage = 'Errore di autenticazione: PIN errato';
|
||||
_intentionalDisconnect = true;
|
||||
_closeChannel();
|
||||
notifyListeners();
|
||||
} else if (type == 'ack') {
|
||||
FeedbackService.triggerSuccess();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// Invia un codice scansionato al PC (tramite WebSocket con fallback HTTP REST)
|
||||
Future<bool> sendCode(String code, {String format = 'Barcode'}) async {
|
||||
final cleanCode = code.trim();
|
||||
if (cleanCode.isEmpty) return false;
|
||||
|
||||
// Trigger visual and haptic feedback
|
||||
await FeedbackService.triggerFeedback(sound: _sound, vibrate: _vibrate);
|
||||
|
||||
bool success = false;
|
||||
|
||||
// 1. Prova tramite WebSocket se connesso
|
||||
if (_status == ConnectionStatus.connected && _channel != null) {
|
||||
try {
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'scan',
|
||||
'code': cleanCode,
|
||||
'suffix': _suffix,
|
||||
'pin': _pin,
|
||||
}));
|
||||
success = true;
|
||||
} catch (_) {
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Se WebSocket non è riuscito o non connesso, fallback su HTTP POST
|
||||
if (!success && _ip.isNotEmpty) {
|
||||
try {
|
||||
final uri = Uri.parse('http://$_ip:$_port/api/type');
|
||||
final res = await http.post(
|
||||
uri,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'code': cleanCode,
|
||||
'suffix': _suffix,
|
||||
'pin': _pin,
|
||||
'source': Platform.isAndroid ? 'Android (HTTP)' : 'iOS (HTTP)',
|
||||
}),
|
||||
).timeout(const Duration(seconds: 2));
|
||||
|
||||
if (res.statusCode == 200) {
|
||||
success = true;
|
||||
}
|
||||
} catch (_) {
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
|
||||
final record = ScanRecord(
|
||||
id: DateTime.now().millisecondsSinceEpoch.toString(),
|
||||
code: cleanCode,
|
||||
format: format,
|
||||
timestamp: DateTime.now(),
|
||||
sentSuccessfully: success,
|
||||
);
|
||||
|
||||
_lastScan = record;
|
||||
_history.insert(0, record);
|
||||
if (_history.length > 200) {
|
||||
_history.removeRange(200, _history.length);
|
||||
}
|
||||
await StorageService.addHistoryItem(record);
|
||||
|
||||
notifyListeners();
|
||||
return success;
|
||||
}
|
||||
|
||||
Future<void> clearHistory() async {
|
||||
_history.clear();
|
||||
_lastScan = null;
|
||||
await StorageService.clearHistory();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_intentionalDisconnect = true;
|
||||
_reconnectTimer?.cancel();
|
||||
_pingTimer?.cancel();
|
||||
_closeChannel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
class DiscoveredServer {
|
||||
final String ip;
|
||||
final int port;
|
||||
final String serverName;
|
||||
final String wsUrl;
|
||||
final String httpUrl;
|
||||
final bool pinRequired;
|
||||
|
||||
DiscoveredServer({
|
||||
required this.ip,
|
||||
required this.port,
|
||||
required this.serverName,
|
||||
required this.wsUrl,
|
||||
required this.httpUrl,
|
||||
required this.pinRequired,
|
||||
});
|
||||
|
||||
factory DiscoveredServer.fromJson(Map<String, dynamic> json) => DiscoveredServer(
|
||||
ip: json['ip'] as String? ?? '',
|
||||
port: json['port'] as int? ?? 8765,
|
||||
serverName: json['server_name'] as String? ?? 'PC Server',
|
||||
wsUrl: json['ws_url'] as String? ?? '',
|
||||
httpUrl: json['http_url'] as String? ?? '',
|
||||
pinRequired: json['pin_required'] as bool? ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
class DiscoveryService {
|
||||
static const int udpPort = 8766;
|
||||
|
||||
static Future<List<DiscoveredServer>> discover({Duration timeout = const Duration(seconds: 3)}) async {
|
||||
final Map<String, DiscoveredServer> found = {};
|
||||
RawDatagramSocket? socket;
|
||||
|
||||
try {
|
||||
socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
|
||||
socket.broadcastEnabled = true;
|
||||
|
||||
// Broadcast message to local network
|
||||
final data = utf8.encode('DISCOVER_BARCODE_SERVER');
|
||||
socket.send(data, InternetAddress('255.255.255.255'), udpPort);
|
||||
|
||||
final completer = Completer<List<DiscoveredServer>>();
|
||||
|
||||
final sub = socket.listen((event) {
|
||||
if (event == RawSocketEvent.read) {
|
||||
final dg = socket?.receive();
|
||||
if (dg != null) {
|
||||
try {
|
||||
final raw = utf8.decode(dg.data).trim();
|
||||
final json = jsonDecode(raw) as Map<String, dynamic>;
|
||||
if (json['type'] == 'discover_response') {
|
||||
final server = DiscoveredServer.fromJson(json);
|
||||
final key = '${server.ip}:${server.port}';
|
||||
found[key] = server;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Timer(timeout, () {
|
||||
sub.cancel();
|
||||
socket?.close();
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(found.values.toList());
|
||||
}
|
||||
});
|
||||
|
||||
return await completer.future;
|
||||
} catch (e) {
|
||||
socket?.close();
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../models/scan_record.dart';
|
||||
|
||||
class StorageService {
|
||||
static const _keyIp = 'server_ip';
|
||||
static const _keyPort = 'server_port';
|
||||
static const _keyPin = 'server_pin';
|
||||
static const _keyServerName = 'server_name';
|
||||
static const _keySuffix = 'server_suffix';
|
||||
static const _keyContinuous = 'continuous_mode';
|
||||
static const _keyVibrate = 'vibrate_enabled';
|
||||
static const _keySound = 'sound_enabled';
|
||||
static const _keyHistory = 'scan_history';
|
||||
|
||||
static Future<Map<String, dynamic>> loadSettings() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return {
|
||||
'ip': prefs.getString(_keyIp) ?? '',
|
||||
'port': prefs.getInt(_keyPort) ?? 8765,
|
||||
'pin': prefs.getString(_keyPin) ?? '',
|
||||
'serverName': prefs.getString(_keyServerName) ?? '',
|
||||
'suffix': prefs.getString(_keySuffix) ?? 'enter',
|
||||
'continuous': prefs.getBool(_keyContinuous) ?? false,
|
||||
'vibrate': prefs.getBool(_keyVibrate) ?? true,
|
||||
'sound': prefs.getBool(_keySound) ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
static Future<void> saveServerConnection({
|
||||
required String ip,
|
||||
required int port,
|
||||
required String pin,
|
||||
String? serverName,
|
||||
}) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyIp, ip);
|
||||
await prefs.setInt(_keyPort, port);
|
||||
await prefs.setString(_keyPin, pin);
|
||||
if (serverName != null) {
|
||||
await prefs.setString(_keyServerName, serverName);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> saveSuffix(String suffix) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keySuffix, suffix);
|
||||
}
|
||||
|
||||
static Future<void> saveContinuousMode(bool enabled) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyContinuous, enabled);
|
||||
}
|
||||
|
||||
static Future<void> saveFeedbackToggles({required bool vibrate, required bool sound}) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyVibrate, vibrate);
|
||||
await prefs.setBool(_keySound, sound);
|
||||
}
|
||||
|
||||
static Future<List<ScanRecord>> loadHistory() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getStringList(_keyHistory) ?? [];
|
||||
return raw.map((item) {
|
||||
try {
|
||||
return ScanRecord.fromJson(jsonDecode(item) as Map<String, dynamic>);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}).whereType<ScanRecord>().toList();
|
||||
}
|
||||
|
||||
static Future<void> addHistoryItem(ScanRecord record) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final history = await loadHistory();
|
||||
history.insert(0, record);
|
||||
if (history.length > 200) {
|
||||
history.removeRange(200, history.length);
|
||||
}
|
||||
final raw = history.map((e) => jsonEncode(e.toJson())).toList();
|
||||
await prefs.setStringList(_keyHistory, raw);
|
||||
}
|
||||
|
||||
static Future<void> clearHistory() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyHistory);
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ScannerOverlay extends StatelessWidget {
|
||||
const ScannerOverlay({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth * 0.82;
|
||||
final height = constraints.maxHeight * 0.40;
|
||||
final left = (constraints.maxWidth - width) / 2;
|
||||
final top = (constraints.maxHeight - height) / 2;
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// Sfondo semi-trasparente scuro con ritaglio centrale
|
||||
ColorFiltered(
|
||||
colorFilter: const ColorFilter.mode(
|
||||
Colors.black54,
|
||||
BlendMode.srcOut,
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
Container(
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.transparent,
|
||||
),
|
||||
child: Container(
|
||||
margin: EdgeInsets.fromLTRB(left, top, left, constraints.maxHeight - top - height),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Cornice angoli del mirino
|
||||
Positioned(
|
||||
left: left,
|
||||
top: top,
|
||||
width: width,
|
||||
height: height,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.8),
|
||||
width: 2.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Linea rossa guida centrale stile laser
|
||||
Positioned(
|
||||
left: left + 16,
|
||||
top: top + (height / 2) - 1,
|
||||
width: width - 32,
|
||||
height: 2,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.redAccent.withValues(alpha: 0.85),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.redAccent.withValues(alpha: 0.6),
|
||||
blurRadius: 4,
|
||||
spreadRadius: 1,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.13.1"
|
||||
bloc:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: bloc
|
||||
sha256: e03b235924e4f509c27b5d6b2f949200e0a91149a9818b4f65eeb56662b75413
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "9.2.1"
|
||||
boolean_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -65,6 +73,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.9"
|
||||
equatable:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: equatable
|
||||
sha256: ea36e500cbf0ec18361deabca755434f73e42fe53c5130021c7e2d6b5ebe1702
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.0"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -94,6 +110,14 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_bloc:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_bloc
|
||||
sha256: cf51747952201a455a1c840f8171d273be009b932c75093020f9af64f2123e38
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "9.1.1"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -208,6 +232,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.5.0"
|
||||
nested:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: nested
|
||||
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
package_config:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -264,6 +296,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.8"
|
||||
provider:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: provider
|
||||
sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.1.5+1"
|
||||
shared_preferences:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
|
||||
@@ -38,6 +38,8 @@ dependencies:
|
||||
web_socket_channel: ^3.0.3
|
||||
http: ^1.6.0
|
||||
shared_preferences: ^2.5.6
|
||||
flutter_bloc: ^9.1.1
|
||||
equatable: ^3.0.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:barcode_reader_app/core/services/feedback_service.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/datasources/connection_local_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/datasources/udp_discovery_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/repositories/connection_repository_impl.dart';
|
||||
import 'package:barcode_reader_app/features/connection/domain/entities/server_connection_info.dart';
|
||||
import 'package:barcode_reader_app/features/connection/domain/repositories/connection_repository.dart';
|
||||
import 'package:barcode_reader_app/features/connection/presentation/cubit/connection_cubit.dart';
|
||||
import 'package:barcode_reader_app/features/scanner/data/datasources/scan_history_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/scanner/data/repositories/scan_repository_impl.dart';
|
||||
import 'package:barcode_reader_app/features/scanner/domain/entities/scan_record.dart';
|
||||
import 'package:barcode_reader_app/features/scanner/presentation/cubit/history_cubit.dart';
|
||||
import 'package:barcode_reader_app/features/scanner/presentation/cubit/scanner_cubit.dart';
|
||||
import 'package:barcode_reader_app/features/settings/data/datasources/settings_local_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/settings/data/repositories/settings_repository_impl.dart';
|
||||
import 'package:barcode_reader_app/features/settings/presentation/cubit/settings_cubit.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late SharedPreferences prefs;
|
||||
late SettingsRepositoryImpl settingsRepo;
|
||||
late ConnectionRepositoryImpl connectionRepo;
|
||||
late ScanRepositoryImpl scanRepo;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
prefs = await SharedPreferences.getInstance();
|
||||
|
||||
settingsRepo = SettingsRepositoryImpl(SettingsLocalDataSource(prefs));
|
||||
connectionRepo = ConnectionRepositoryImpl(
|
||||
localDataSource: ConnectionLocalDataSource(prefs),
|
||||
remoteDataSource: ConnectionRemoteDataSource(),
|
||||
discoveryDataSource: const UdpDiscoveryDataSource(),
|
||||
);
|
||||
scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
connectionRepo.dispose();
|
||||
});
|
||||
|
||||
group('SettingsCubit', () {
|
||||
test('updates suffix and persists', () async {
|
||||
final cubit = SettingsCubit(settingsRepo);
|
||||
await cubit.loadSettings();
|
||||
expect(cubit.state.settings.suffix, 'enter');
|
||||
|
||||
await cubit.updateSuffix('tab');
|
||||
expect(cubit.state.settings.suffix, 'tab');
|
||||
|
||||
final reloaded = await settingsRepo.loadSettings();
|
||||
expect(reloaded.suffix, 'tab');
|
||||
});
|
||||
|
||||
test('updates continuous mode and feedback settings', () async {
|
||||
final cubit = SettingsCubit(settingsRepo);
|
||||
await cubit.loadSettings();
|
||||
|
||||
await cubit.updateContinuousMode(true);
|
||||
expect(cubit.state.settings.continuousMode, true);
|
||||
|
||||
await cubit.updateFeedback(vibrate: false, sound: false);
|
||||
expect(cubit.state.settings.vibrate, false);
|
||||
expect(cubit.state.settings.sound, false);
|
||||
});
|
||||
});
|
||||
|
||||
group('HistoryCubit', () {
|
||||
test('adds scan and filters correctly', () async {
|
||||
final cubit = HistoryCubit(scanRepo);
|
||||
await cubit.loadHistory();
|
||||
expect(cubit.state.history, isEmpty);
|
||||
|
||||
final record1 = ScanRecord(
|
||||
id: '1',
|
||||
code: '1234567890',
|
||||
format: 'EAN_13',
|
||||
timestamp: DateTime.now(),
|
||||
sentSuccessfully: true,
|
||||
);
|
||||
final record2 = ScanRecord(
|
||||
id: '2',
|
||||
code: 'ABC-999',
|
||||
format: 'CODE_128',
|
||||
timestamp: DateTime.now(),
|
||||
sentSuccessfully: false,
|
||||
);
|
||||
|
||||
await cubit.addScan(record1);
|
||||
await cubit.addScan(record2);
|
||||
|
||||
expect(cubit.state.history.length, 2);
|
||||
|
||||
cubit.setSearchQuery('ABC');
|
||||
expect(cubit.state.filteredHistory.length, 1);
|
||||
expect(cubit.state.filteredHistory.first.code, 'ABC-999');
|
||||
|
||||
cubit.setSearchQuery('');
|
||||
expect(cubit.state.filteredHistory.length, 2);
|
||||
|
||||
await cubit.deleteScan('1');
|
||||
expect(cubit.state.history.length, 1);
|
||||
expect(cubit.state.history.first.id, '2');
|
||||
|
||||
await cubit.clearHistory();
|
||||
expect(cubit.state.history, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('ConnectionCubit', () {
|
||||
test('starts disconnected and handles manual disconnect', () async {
|
||||
final cubit = ConnectionCubit(connectionRepo);
|
||||
await cubit.initialize();
|
||||
|
||||
expect(cubit.state.status, ConnectionStatus.disconnected);
|
||||
|
||||
await cubit.disconnect();
|
||||
expect(cubit.state.status, ConnectionStatus.disconnected);
|
||||
expect(cubit.state.statusMessage, 'Disconnesso manualmente');
|
||||
});
|
||||
});
|
||||
|
||||
group('ScannerCubit', () {
|
||||
test('toggles torch and camera', () {
|
||||
final settingsCubit = SettingsCubit(settingsRepo);
|
||||
final connectionCubit = ConnectionCubit(connectionRepo);
|
||||
final historyCubit = HistoryCubit(scanRepo);
|
||||
|
||||
final scannerCubit = ScannerCubit(
|
||||
connectionCubit: connectionCubit,
|
||||
settingsCubit: settingsCubit,
|
||||
historyCubit: historyCubit,
|
||||
feedbackService: const FeedbackService(),
|
||||
);
|
||||
|
||||
expect(scannerCubit.state.isTorchOn, false);
|
||||
scannerCubit.toggleTorch();
|
||||
expect(scannerCubit.state.isTorchOn, true);
|
||||
|
||||
expect(scannerCubit.state.isFrontCamera, false);
|
||||
scannerCubit.toggleCamera();
|
||||
expect(scannerCubit.state.isFrontCamera, true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,15 +1,39 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:barcode_reader_app/main.dart';
|
||||
import 'package:barcode_reader_app/services/connection_service.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:barcode_reader_app/main.dart';
|
||||
import 'package:barcode_reader_app/core/services/feedback_service.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/datasources/connection_local_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/datasources/udp_discovery_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/connection/data/repositories/connection_repository_impl.dart';
|
||||
import 'package:barcode_reader_app/features/scanner/data/datasources/scan_history_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/scanner/data/repositories/scan_repository_impl.dart';
|
||||
import 'package:barcode_reader_app/features/settings/data/datasources/settings_local_datasource.dart';
|
||||
import 'package:barcode_reader_app/features/settings/data/repositories/settings_repository_impl.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('App initialization test', (WidgetTester tester) async {
|
||||
testWidgets('App initialization test with Bloc/Cubit', (WidgetTester tester) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final service = ConnectionService();
|
||||
await service.initialize();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
final settingsRepo = SettingsRepositoryImpl(SettingsLocalDataSource(prefs));
|
||||
final connectionRepo = ConnectionRepositoryImpl(
|
||||
localDataSource: ConnectionLocalDataSource(prefs),
|
||||
remoteDataSource: ConnectionRemoteDataSource(),
|
||||
discoveryDataSource: const UdpDiscoveryDataSource(),
|
||||
);
|
||||
final scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
|
||||
const feedbackService = FeedbackService();
|
||||
|
||||
await tester.pumpWidget(
|
||||
BarcodeReaderApp(
|
||||
settingsRepository: settingsRepo,
|
||||
connectionRepository: connectionRepo,
|
||||
scanRepository: scanRepo,
|
||||
feedbackService: feedbackService,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(BarcodeReaderApp(connectionService: service));
|
||||
expect(find.byType(BarcodeReaderApp), findsOneWidget);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user