Co-authored-by: Azareth-Tr <Azareth-Tr@users.noreply.github.com>
Co-authored-by: MENDOZA BALLARDO GAEL RICARDO <gael-meb123@users.noreply.github.com>

vistas
This commit is contained in:
shinra32
2026-05-23 00:45:34 -06:00
parent c58fa571aa
commit 3a3178eb3b
15 changed files with 527 additions and 4237 deletions

View File

@@ -14,14 +14,9 @@ import 'package:recolecta_app/features/home/citizen_shell.dart';
import 'package:recolecta_app/features/separation_guide/screens/category_detail_screen.dart'; import 'package:recolecta_app/features/separation_guide/screens/category_detail_screen.dart';
import 'package:recolecta_app/features/separation_guide/screens/separation_guide_screen.dart'; import 'package:recolecta_app/features/separation_guide/screens/separation_guide_screen.dart';
import 'package:recolecta_app/core/services/auth_controller.dart'; import 'package:recolecta_app/core/services/auth_controller.dart';
import '../../features/admin/screens/admin_dashboard_screen.dart';
// Mock Admin Screens import '../../features/notifications/notifications_screen.dart';
class AdminDashboardScreen extends StatelessWidget { import '../../features/quiz/quiz_screen.dart';
const AdminDashboardScreen({super.key});
@override
Widget build(BuildContext context) =>
const Scaffold(body: Center(child: Text('Admin Dashboard')));
}
class AdminRouteDetailScreen extends StatelessWidget { class AdminRouteDetailScreen extends StatelessWidget {
const AdminRouteDetailScreen({super.key, required this.routeId}); const AdminRouteDetailScreen({super.key, required this.routeId});
@@ -142,6 +137,11 @@ final routerProvider = Provider<GoRouter>((ref) {
), ),
], ],
), ),
GoRoute(
path: '/notifications',
builder: (context, state) => const NotificationsScreen(),
),
GoRoute(path: '/quiz', builder: (context, state) => const QuizScreen()),
], ],
); );
}); });

View File

@@ -1,3 +1,4 @@
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/auth_state.dart'; import '../models/auth_state.dart';
@@ -14,28 +15,28 @@ class AuthController extends AsyncNotifier<AuthState> {
if (session == null) { if (session == null) {
return const AuthState.unauthenticated(); return const AuthState.unauthenticated();
} }
final authState = AuthState.authenticated(
return AuthState.authenticated(
token: session.token, token: session.token,
userRole: session.userRole, userRole: session.userRole,
routeId: session.routeId, routeId: session.routeId,
); );
_subscribeIfCitizen(authState);
return authState;
} }
Future<void> login({required String email, required String password}) async { Future<void> login({required String email, required String password}) async {
state = const AsyncLoading<AuthState>(); state = const AsyncLoading<AuthState>();
try { try {
final session = await ref final session = await ref
.read(authServiceProvider) .read(authServiceProvider)
.login(email: email, password: password); .login(email: email, password: password);
state = AsyncData( final authState = AuthState.authenticated(
AuthState.authenticated(
token: session.token, token: session.token,
userRole: session.userRole, userRole: session.userRole,
routeId: session.routeId, routeId: session.routeId,
),
); );
_subscribeIfCitizen(authState);
state = AsyncData(authState);
} catch (error, stackTrace) { } catch (error, stackTrace) {
state = AsyncError<AuthState>(error, stackTrace); state = AsyncError<AuthState>(error, stackTrace);
rethrow; rethrow;
@@ -48,18 +49,17 @@ class AuthController extends AsyncNotifier<AuthState> {
required String password, required String password,
}) async { }) async {
state = const AsyncLoading<AuthState>(); state = const AsyncLoading<AuthState>();
try { try {
final session = await ref final session = await ref
.read(authServiceProvider) .read(authServiceProvider)
.register(email: email, phone: phone, password: password); .register(email: email, phone: phone, password: password);
state = AsyncData( final authState = AuthState.authenticated(
AuthState.authenticated(
token: session.token, token: session.token,
userRole: session.userRole, userRole: session.userRole,
routeId: session.routeId, routeId: session.routeId,
),
); );
_subscribeIfCitizen(authState);
state = AsyncData(authState);
} catch (error, stackTrace) { } catch (error, stackTrace) {
state = AsyncError<AuthState>(error, stackTrace); state = AsyncError<AuthState>(error, stackTrace);
rethrow; rethrow;
@@ -67,7 +67,17 @@ class AuthController extends AsyncNotifier<AuthState> {
} }
Future<void> logout() async { Future<void> logout() async {
final previousRouteId = state.value?.routeId;
await ref.read(authServiceProvider).logout(); await ref.read(authServiceProvider).logout();
if (previousRouteId != null) {
FirebaseMessaging.instance.unsubscribeFromTopic('topic_$previousRouteId');
}
state = const AsyncData(AuthState.unauthenticated()); state = const AsyncData(AuthState.unauthenticated());
} }
void _subscribeIfCitizen(AuthState authState) {
if (authState.userRole == 'citizen' && authState.routeId != null) {
FirebaseMessaging.instance.subscribeToTopic('topic_${authState.routeId}');
}
}
} }

View File

@@ -0,0 +1,307 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:latlong2/latlong.dart';
import '../../../../core/constants/auth_constants.dart';
import '../../../../core/theme/app_theme.dart';
const _kRelleno = LatLng(20.5111, -100.9037);
const _kRouteColors = [
Colors.blue,
Colors.green,
Colors.orange,
Colors.red,
Colors.purple,
Colors.teal,
];
class _RouteData {
const _RouteData({
required this.routeId,
required this.currentPositionId,
required this.status,
required this.positions,
});
final String routeId;
final int currentPositionId;
final String status;
final List<LatLng> positions;
}
class AdminDashboardScreen extends StatefulWidget {
const AdminDashboardScreen({super.key});
@override
State<AdminDashboardScreen> createState() => _AdminDashboardScreenState();
}
class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
List<_RouteData> _routes = [];
bool _isLoading = true;
String? _error;
@override
void initState() {
super.initState();
_loadRoutes();
}
Future<void> _loadRoutes() async {
setState(() {
_isLoading = true;
_error = null;
});
try {
const storage = FlutterSecureStorage();
final token = await storage.read(key: authTokenStorageKey) ?? '';
final dio = Dio(
BaseOptions(
baseUrl: const String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://10.0.2.2:8000',
),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
),
);
final routesRes = await dio.get<List<dynamic>>('/routes');
final routeList = routesRes.data ?? [];
final List<_RouteData> loaded = [];
for (final r in routeList) {
final routeId = (r['route_id'] ?? r['id'] ?? '').toString();
if (routeId.isEmpty) continue;
List<LatLng> positions = [];
try {
final posRes = await dio.get<List<dynamic>>('/routes/$routeId/positions');
positions = (posRes.data ?? [])
.map<LatLng>((p) => LatLng(
(p['lat'] as num).toDouble(),
(p['lng'] as num).toDouble(),
))
.toList();
} catch (_) {}
loaded.add(_RouteData(
routeId: routeId,
currentPositionId: (r['current_position_id'] as int?) ?? 1,
status: (r['status'] ?? 'pendiente').toString(),
positions: positions,
));
}
if (mounted) {
setState(() {
_routes = loaded;
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_error = e.toString();
_isLoading = false;
});
}
}
}
Marker _buildTruckMarker(_RouteData route, Color color) {
final posIdx = (route.currentPositionId - 1).clamp(0, route.positions.length - 1);
return Marker(
point: route.positions[posIdx],
width: 48,
height: 48,
child: Tooltip(
message: '${route.routeId} · pos ${route.currentPositionId} · ${route.status}',
child: Container(
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 2),
),
child: const Icon(Icons.local_shipping, color: Colors.white, size: 22),
),
),
);
}
@override
Widget build(BuildContext context) {
final routesWithPos = _routes.where((r) => r.positions.isNotEmpty).toList();
return Scaffold(
appBar: AppBar(
title: const Text('Panel de Control - Flotilla'),
backgroundColor: AppTheme.primaryDark,
foregroundColor: Colors.white,
elevation: 0,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadRoutes,
tooltip: 'Actualizar',
),
],
),
body: Column(
children: [
Container(
width: double.infinity,
color: AppTheme.amberLight,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: const Row(
children: [
Icon(Icons.security, color: AppTheme.amber, size: 20),
SizedBox(width: 10),
Expanded(
child: Text(
'Privilegio Admin: Vista global de coordenadas. No compartir pantalla.',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: AppTheme.amber,
),
),
),
],
),
),
Expanded(
child: Stack(
children: [
FlutterMap(
options: const MapOptions(
initialCenter: _kRelleno,
initialZoom: 12.5,
interactionOptions: InteractionOptions(
flags: InteractiveFlag.all,
),
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.onlineshack.recolecta',
),
if (routesWithPos.isNotEmpty) ...[
PolylineLayer(
polylines: [
for (int i = 0; i < routesWithPos.length; i++)
if (routesWithPos[i].positions.length > 1)
Polyline(
points: routesWithPos[i].positions,
color: _kRouteColors[i % _kRouteColors.length]
.withValues(alpha: 0.7),
strokeWidth: 3.5,
),
],
),
MarkerLayer(
markers: [
for (int i = 0; i < routesWithPos.length; i++)
_buildTruckMarker(
routesWithPos[i],
_kRouteColors[i % _kRouteColors.length],
),
],
),
],
],
),
if (_isLoading)
const Center(child: CircularProgressIndicator()),
if (_error != null && !_isLoading)
Positioned(
bottom: 16,
left: 16,
right: 16,
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppTheme.danger.withValues(alpha: 0.9),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Sin conexión al backend: $_error',
style: const TextStyle(
color: Colors.white,
fontSize: 12,
),
),
),
),
if (routesWithPos.isNotEmpty)
Positioned(
top: 12,
right: 12,
child: _RouteLegend(routes: routesWithPos),
),
],
),
),
],
),
);
}
}
class _RouteLegend extends StatelessWidget {
const _RouteLegend({required this.routes});
final List<_RouteData> routes;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.93),
borderRadius: BorderRadius.circular(8),
boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 4)],
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (int i = 0; i < routes.length; i++)
Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 10,
height: 10,
decoration: BoxDecoration(
color: _kRouteColors[i % _kRouteColors.length],
shape: BoxShape.circle,
),
),
const SizedBox(width: 6),
Text(
'${routes[i].routeId} · pos ${routes[i].currentPositionId}',
style: const TextStyle(
fontSize: 10,
color: AppTheme.textPrimary,
),
),
],
),
),
],
),
);
}
}

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
@@ -43,6 +44,7 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
bool _obscurePass = true; bool _obscurePass = true;
// Paso 2 // Paso 2
final _mapController = MapController();
final _cpCtrl = TextEditingController(); final _cpCtrl = TextEditingController();
final _calleCtrl = TextEditingController(); final _calleCtrl = TextEditingController();
Colonia? _selectedColonia; Colonia? _selectedColonia;
@@ -92,6 +94,7 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
_passCtrl.dispose(); _passCtrl.dispose();
_calleCtrl.dispose(); _calleCtrl.dispose();
_cpCtrl.dispose(); _cpCtrl.dispose();
_mapController.dispose();
super.dispose(); super.dispose();
} }
@@ -119,7 +122,9 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
'format': 'json', 'format': 'json',
'addressdetails': 1, 'addressdetails': 1,
}, },
options: Options(headers: {'User-Agent': 'com.onlineshack.recolecta'}), options: kIsWeb
? null
: Options(headers: {'User-Agent': 'com.onlineshack.recolecta'}),
); );
if (response.data != null && response.data['address'] != null) { if (response.data != null && response.data['address'] != null) {
@@ -194,32 +199,11 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
FocusScope.of(context).unfocus(); // Cierra el teclado FocusScope.of(context).unfocus(); // Cierra el teclado
} }
Future<void> _register() async { Future<void> _postAddressInBackground(String calle, String colonia) async {
if (_calleCtrl.text.trim().isEmpty || _selectedColonia == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ingresa tu calle y selecciona una colonia'),
behavior: SnackBarBehavior.floating,
),
);
return;
}
// 1. Registra al usuario
await ref
.read(authControllerProvider.notifier)
.register(
email: _emailCtrl.text.trim(),
phone: _telefonoCtrl.text.trim(),
password: _passCtrl.text,
);
// Detenernos si hubo algún error en el auth (ej. contraseña corta)
if (ref.read(authControllerProvider).hasError) return;
// 2. Guardar la dirección en el backend de forma silenciosa
try { try {
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
// Esperar un momento para asegurar que el token se haya guardado
await Future.delayed(const Duration(milliseconds: 500));
final token = await storage.read(key: 'token') ?? ''; final token = await storage.read(key: 'token') ?? '';
if (token.isNotEmpty) { if (token.isNotEmpty) {
@@ -235,33 +219,51 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
await dio.post( await dio.post(
'/addresses', '/addresses',
data: { data: {'label': 'Mi Casa', 'calle': calle, 'colonia': colonia},
'label': 'Mi Casa',
'calle': _calleCtrl.text.trim(),
'colonia': _selectedColonia!.nombre,
},
); );
} }
} catch (e) { } catch (e) {
debugPrint('Aviso: No se pudo guardar la dirección inicial: $e'); debugPrint('Aviso: No se pudo guardar la dirección inicial: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Error al guardar tu dirección. Inténtalo más tarde.',
),
backgroundColor: AppTheme.danger,
),
);
} }
return; // No navegar si falla el guardado de la dirección
} }
// 3. Navegar a inicio de manera limpia Future<void> _register() async {
if (_calleCtrl.text.trim().isEmpty || _selectedColonia == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ingresa tu calle y selecciona una colonia'),
behavior: SnackBarBehavior.floating,
),
);
return;
}
// Capturar variables antes del proceso asíncrono
final calle = _calleCtrl.text.trim();
final colonia = _selectedColonia!.nombre;
// 1. Registra al usuario
await ref
.read(authControllerProvider.notifier)
.register(
email: _emailCtrl.text.trim(),
phone: _telefonoCtrl.text.trim(),
password: _passCtrl.text,
);
// Si el widget ya no está montado, GoRouter nos redirigió automáticamente al Home por éxito.
if (!mounted) {
_postAddressInBackground(calle, colonia);
return;
}
// Si seguimos aquí, verificar si hubo un error (ej. contraseña corta)
if (ref.read(authControllerProvider).hasError) return;
// Fallback: guardar dirección y navegar manualmente
await _postAddressInBackground(calle, colonia);
if (mounted) { if (mounted) {
context.go( context.go('/home');
'/home',
); // ¡Solución al GoException! Navega a la ruta correcta
} }
} }
@@ -300,6 +302,7 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
onNext: _nextPage, onNext: _nextPage,
), ),
_Step2( _Step2(
mapController: _mapController,
cpCtrl: _cpCtrl, cpCtrl: _cpCtrl,
calleCtrl: _calleCtrl, calleCtrl: _calleCtrl,
selectedColonia: _selectedColonia, selectedColonia: _selectedColonia,
@@ -480,6 +483,7 @@ class _Step1 extends StatelessWidget {
// ── Paso 2: Dirección ───────────────────────────────────────────────────────── // ── Paso 2: Dirección ─────────────────────────────────────────────────────────
class _Step2 extends StatelessWidget { class _Step2 extends StatelessWidget {
final MapController mapController;
final TextEditingController cpCtrl; final TextEditingController cpCtrl;
final TextEditingController calleCtrl; final TextEditingController calleCtrl;
final Colonia? selectedColonia; final Colonia? selectedColonia;
@@ -494,6 +498,7 @@ class _Step2 extends StatelessWidget {
final VoidCallback onRegister; final VoidCallback onRegister;
const _Step2({ const _Step2({
required this.mapController,
required this.cpCtrl, required this.cpCtrl,
required this.calleCtrl, required this.calleCtrl,
required this.selectedColonia, required this.selectedColonia,
@@ -510,13 +515,19 @@ class _Step2 extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final mapCenter = selectedLocation ?? const LatLng(20.5222, -100.8123); // Usamos el centro original de la colonia para los límites estáticos
final baseCenter = selectedColonia != null
? kColoniasCoordinates[selectedColonia!.nombre] ??
const LatLng(20.5222, -100.8123)
: const LatLng(20.5222, -100.8123);
// Magia de privacidad: Restringir paneo a 1km a la redonda de la colonia final mapCenter = selectedLocation ?? baseCenter;
// Magia de privacidad: Restringir paneo a 1km a la redonda usando el centro original
final bounds = selectedColonia != null final bounds = selectedColonia != null
? LatLngBounds( ? LatLngBounds(
LatLng(mapCenter.latitude - 0.01, mapCenter.longitude - 0.01), LatLng(baseCenter.latitude - 0.01, baseCenter.longitude - 0.01),
LatLng(mapCenter.latitude + 0.01, mapCenter.longitude + 0.01), LatLng(baseCenter.latitude + 0.01, baseCenter.longitude + 0.01),
) )
: null; : null;
@@ -542,6 +553,8 @@ class _Step2 extends StatelessWidget {
Row( Row(
children: [ children: [
Expanded( Expanded(
child: Material(
color: Colors.transparent,
child: RadioListTile<String>( child: RadioListTile<String>(
title: const Text( title: const Text(
'Casa', 'Casa',
@@ -552,7 +565,10 @@ class _Step2 extends StatelessWidget {
onChanged: (v) => onTipoChanged(v!), onChanged: (v) => onTipoChanged(v!),
), ),
), ),
),
Expanded( Expanded(
child: Material(
color: Colors.transparent,
child: RadioListTile<String>( child: RadioListTile<String>(
title: const Text( title: const Text(
'Negocio', 'Negocio',
@@ -563,6 +579,7 @@ class _Step2 extends StatelessWidget {
onChanged: (v) => onTipoChanged(v!), onChanged: (v) => onTipoChanged(v!),
), ),
), ),
),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
@@ -647,12 +664,12 @@ class _Step2 extends StatelessWidget {
), ),
clipBehavior: Clip.hardEdge, clipBehavior: Clip.hardEdge,
child: FlutterMap( child: FlutterMap(
key: ValueKey(selectedColonia?.nombre ?? 'default'), mapController: mapController,
options: MapOptions( options: MapOptions(
initialCenter: mapCenter, initialCenter: mapCenter,
initialZoom: 15.0, initialZoom: 15.0,
cameraConstraint: bounds != null cameraConstraint: bounds != null
? CameraConstraint.contain(bounds: bounds) ? CameraConstraint.containCenter(bounds: bounds)
: const CameraConstraint.unconstrained(), : const CameraConstraint.unconstrained(),
onTap: (_, latlng) => onLocationChanged(latlng), onTap: (_, latlng) => onLocationChanged(latlng),
), ),
@@ -746,7 +763,9 @@ class _Step2 extends StatelessWidget {
title: 'Notificaciones Externas', title: 'Notificaciones Externas',
child: Column( child: Column(
children: [ children: [
CheckboxListTile( Material(
color: Colors.transparent,
child: CheckboxListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
controlAffinity: ListTileControlAffinity.leading, controlAffinity: ListTileControlAffinity.leading,
activeColor: AppTheme.primary, activeColor: AppTheme.primary,
@@ -754,7 +773,11 @@ class _Step2 extends StatelessWidget {
onChanged: onWhatsappChanged, onChanged: onWhatsappChanged,
title: const Text( title: const Text(
'Recibir alertas del camión vía WhatsApp (Próximamente)', 'Recibir alertas del camión vía WhatsApp (Próximamente)',
style: TextStyle(fontSize: 14, color: AppTheme.textPrimary), style: TextStyle(
fontSize: 14,
color: AppTheme.textPrimary,
),
),
), ),
), ),
], ],

View File

@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
import '../../core/theme/app_theme.dart';
class NotificationsScreen extends StatelessWidget {
const NotificationsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppTheme.background,
appBar: AppBar(title: const Text('Avisos y Alertas')),
body: const Center(
child: Text(
'Bandeja de entrada de FCM',
style: TextStyle(color: AppTheme.textSecondary),
),
),
);
}
}

View File

@@ -0,0 +1,21 @@
// Vista de Educación y Quiz
import 'package:flutter/material.dart';
import '../../core/theme/app_theme.dart';
class QuizScreen extends StatelessWidget {
const QuizScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppTheme.background,
appBar: AppBar(title: const Text('Educación y Quiz')),
body: const Center(
child: Text(
'Chat IA / Guía de separación offline',
style: TextStyle(color: AppTheme.textSecondary),
),
),
);
}
}

View File

@@ -1,11 +1,36 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'app/app.dart'; import 'app/app.dart';
import 'firebase_options.dart';
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
} catch (_) {}
debugPrint('FCM background: ${message.messageId} | data: ${message.data}');
}
Future<void> main() async { Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
await dotenv.load(fileName: '.env'); try {
await dotenv.load(fileName: 'assets/.env');
} catch (_) {
// .env no disponible — api_client.dart usa los valores por defecto
}
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
} on UnsupportedError {
await Firebase.initializeApp();
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(const ProviderScope(child: RecolectaApp())); runApp(const ProviderScope(child: RecolectaApp()));
} }

View File

@@ -63,6 +63,7 @@ dev_dependencies:
flutter: flutter:
assets: assets:
# - assets/images/ # - assets/images/
- assets/.env
- assets/data/separation_guide.json - assets/data/separation_guide.json
# The following line ensures that the Material Icons font is # The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in # included with your application, so that you can use the icons in

File diff suppressed because it is too large Load Diff

View File

@@ -12,7 +12,7 @@ class AlertsScreen extends StatefulWidget {
class _AlertsScreenState extends State<AlertsScreen> { class _AlertsScreenState extends State<AlertsScreen> {
// Alerta activa de ejemplo // Alerta activa de ejemplo
final AlertaModel _alertaActiva = AlertaModel( final AlertaModel? _alertaActiva = AlertaModel(
id: 'alerta-001', id: 'alerta-001',
tipo: TipoAlerta.cercana, tipo: TipoAlerta.cercana,
distanciaMetros: 180, distanciaMetros: 180,
@@ -220,7 +220,7 @@ class _AlertaActivaCard extends StatelessWidget {
borderRadius: BorderRadius.circular(4), borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: progreso, value: progreso,
backgroundColor: AppTheme.primaryMid.withValues(alpha: 0.4), backgroundColor: AppTheme.primaryMid.withOpacity(0.4),
valueColor: const AlwaysStoppedAnimation<Color>(AppTheme.primary), valueColor: const AlwaysStoppedAnimation<Color>(AppTheme.primary),
minHeight: 7, minHeight: 7,
), ),

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../theme/app_theme.dart'; import '../theme/app_theme.dart';
import '../widgets/widgets.dart' as w; import '../widgets/widgets.dart' as w;
import 'admin_screen.dart';
import 'driver_screen.dart';
import 'main_shell.dart'; import 'main_shell.dart';
enum UserRole { usuario, conductor, administrador }
class LoginScreen extends StatefulWidget { class LoginScreen extends StatefulWidget {
const LoginScreen({super.key}); const LoginScreen({super.key});
@@ -18,7 +14,6 @@ class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
final _emailCtrl = TextEditingController(); final _emailCtrl = TextEditingController();
final _passCtrl = TextEditingController(); final _passCtrl = TextEditingController();
UserRole _selectedRole = UserRole.usuario;
bool _obscurePass = true; bool _obscurePass = true;
bool _loading = false; bool _loading = false;
@@ -37,22 +32,11 @@ class _LoginScreenState extends State<LoginScreen> {
setState(() => _loading = false); setState(() => _loading = false);
Navigator.pushAndRemoveUntil( Navigator.pushAndRemoveUntil(
context, context,
MaterialPageRoute(builder: (_) => _homeForRole()), MaterialPageRoute(builder: (_) => const MainShell()),
(_) => false, (_) => false,
); );
} }
Widget _homeForRole() {
switch (_selectedRole) {
case UserRole.conductor:
return const DriverShell();
case UserRole.administrador:
return const AdminShell();
case UserRole.usuario:
return const MainShell();
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@@ -135,37 +119,7 @@ class _LoginScreenState extends State<LoginScreen> {
setState(() => _obscurePass = !_obscurePass), setState(() => _obscurePass = !_obscurePass),
), ),
), ),
const SizedBox(height: 16),
DropdownButtonFormField<UserRole>(
initialValue: _selectedRole,
decoration: InputDecoration(
labelText: 'Tipo de usuario',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
),
contentPadding:
const EdgeInsets.symmetric(horizontal: 14, vertical: 16),
),
items: const [
DropdownMenuItem(
value: UserRole.usuario,
child: Text('Usuario'),
),
DropdownMenuItem(
value: UserRole.conductor,
child: Text('Conductor'),
),
DropdownMenuItem(
value: UserRole.administrador,
child: Text('Administrador'),
),
],
onChanged: (value) {
if (value != null) {
setState(() => _selectedRole = value);
}
},
),
const SizedBox(height: 10), const SizedBox(height: 10),
Align( Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,

View File

@@ -33,7 +33,7 @@ class _MapScreenState extends State<MapScreen> {
enServicio: true, enServicio: true,
); );
final HouseModel _casa = HouseModel( final HouseModel _casa = const HouseModel(
id: 'casa-01', id: 'casa-01',
calle: 'Av. Insurgentes 245', calle: 'Av. Insurgentes 245',
colonia: 'Centro', colonia: 'Centro',
@@ -45,6 +45,7 @@ class _MapScreenState extends State<MapScreen> {
Set<Marker> _markers = {}; Set<Marker> _markers = {};
Set<Circle> _circles = {}; Set<Circle> _circles = {};
bool _mapLoaded = false;
Timer? _refreshTimer; Timer? _refreshTimer;
// Distancia simulada (metros) // Distancia simulada (metros)
@@ -91,8 +92,8 @@ class _MapScreenState extends State<MapScreen> {
circleId: const CircleId('radio-alerta'), circleId: const CircleId('radio-alerta'),
center: LatLng(_casa.latitud, _casa.longitud), center: LatLng(_casa.latitud, _casa.longitud),
radius: _casa.radioAlertaMetros.toDouble(), radius: _casa.radioAlertaMetros.toDouble(),
fillColor: AppTheme.blue.withValues(alpha: 0.08), fillColor: AppTheme.blue.withOpacity(0.08),
strokeColor: AppTheme.blue.withValues(alpha: 0.4), strokeColor: AppTheme.blue.withOpacity(0.4),
strokeWidth: 1, strokeWidth: 1,
), ),
}; };
@@ -135,6 +136,7 @@ class _MapScreenState extends State<MapScreen> {
mapType: MapType.normal, mapType: MapType.normal,
onMapCreated: (c) { onMapCreated: (c) {
_mapController.complete(c); _mapController.complete(c);
setState(() => _mapLoaded = true);
}, },
), ),
@@ -289,7 +291,7 @@ class _LiveBadgeState extends State<_LiveBadge>
decoration: BoxDecoration( decoration: BoxDecoration(
shape: BoxShape.circle, shape: BoxShape.circle,
color: widget.activo color: widget.activo
? AppTheme.primary.withValues(alpha: 0.5 + _anim.value * 0.5) ? AppTheme.primary.withOpacity(0.5 + _anim.value * 0.5)
: AppTheme.textSecondary, : AppTheme.textSecondary,
), ),
), ),
@@ -356,7 +358,7 @@ class _ArrivalBar extends StatelessWidget {
borderRadius: BorderRadius.circular(4), borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: progreso, value: progreso,
backgroundColor: AppTheme.primaryMid.withValues(alpha: 0.4), backgroundColor: AppTheme.primaryMid.withOpacity(0.4),
valueColor: valueColor:
const AlwaysStoppedAnimation<Color>(AppTheme.primary), const AlwaysStoppedAnimation<Color>(AppTheme.primary),
minHeight: 6, minHeight: 6,

View File

@@ -111,7 +111,9 @@ class ProfileScreen extends StatelessWidget {
'RutaVerde v1.0.0\nServicio de Limpia · Celaya, Gto.', 'RutaVerde v1.0.0\nServicio de Limpia · Celaya, Gto.',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: const TextStyle( style: const TextStyle(
fontSize: 12, color: AppTheme.textHint, height: 1.6), fontSize: 12,
color: AppTheme.textHint,
height: 1.6),
), ),
), ),
@@ -140,8 +142,7 @@ class ProfileScreen extends StatelessWidget {
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(ctx), onPressed: () => Navigator.pop(ctx),
style: style: TextButton.styleFrom(foregroundColor: AppTheme.textSecondary),
TextButton.styleFrom(foregroundColor: AppTheme.textSecondary),
child: const Text('Cancelar'), child: const Text('Cancelar'),
), ),
TextButton( TextButton(

View File

@@ -67,7 +67,7 @@ class _SplashScreenState extends State<SplashScreen>
width: 90, width: 90,
height: 90, height: 90,
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.15), color: Colors.white.withOpacity(0.15),
borderRadius: borderRadius:
BorderRadius.circular(AppTheme.radiusXl), BorderRadius.circular(AppTheme.radiusXl),
), ),
@@ -103,7 +103,7 @@ class _SplashScreenState extends State<SplashScreen>
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(
fontSize: 15, fontSize: 15,
color: Colors.white.withValues(alpha: 0.82), color: Colors.white.withOpacity(0.82),
height: 1.5, height: 1.5,
), ),
), ),
@@ -189,7 +189,7 @@ class _SplashScreenState extends State<SplashScreen>
'Servicio de Limpia · Celaya, Gto.', 'Servicio de Limpia · Celaya, Gto.',
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 12,
color: Colors.white.withValues(alpha: 0.45), color: Colors.white.withOpacity(0.45),
), ),
), ),
@@ -214,9 +214,9 @@ class _FeatureChip extends StatelessWidget {
return Container( return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.12), color: Colors.white.withOpacity(0.12),
borderRadius: BorderRadius.circular(AppTheme.radiusMd), borderRadius: BorderRadius.circular(AppTheme.radiusMd),
border: Border.all(color: Colors.white.withValues(alpha: 0.2)), border: Border.all(color: Colors.white.withOpacity(0.2)),
), ),
child: Column( child: Column(
children: [ children: [