inicio de estrcutura
This commit is contained in:
520
aplicacion_hack/lib/screens/home_screen.dart
Normal file
520
aplicacion_hack/lib/screens/home_screen.dart
Normal file
@@ -0,0 +1,520 @@
|
||||
// ================================================================
|
||||
// lib/screens/home_screen.dart
|
||||
// Pantalla Principal — Visualización de ETA y Mensajería Preventiva
|
||||
// ================================================================
|
||||
//
|
||||
// PROPÓSITO:
|
||||
// Mostrar de forma CLARA y VISUAL el estado del camión de
|
||||
// recolección y el mensaje preventivo correspondiente.
|
||||
//
|
||||
// FLUJO:
|
||||
// 1. Recibe usuario_id desde LoginScreen (Navigator arguments)
|
||||
// 2. Llama a ApiService.obtenerETA() en initState
|
||||
// 3. Muestra el mensaje preventivo con diseño de alto impacto
|
||||
// 4. Se refresca cada 60 segundos para simular actualización real
|
||||
// 5. Registra el FCM token si Firebase está disponible
|
||||
//
|
||||
// DECISIÓN DE DISEÑO:
|
||||
// El texto del mensaje preventivo es ENORME y ocupa el centro
|
||||
// de la pantalla. En una app real de alertas críticas, la
|
||||
// claridad visual es más importante que la estética.
|
||||
// ================================================================
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
// Descomenta cuando Firebase esté configurado:
|
||||
// import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import '../services/api_service.dart';
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
const HomeScreen({super.key});
|
||||
|
||||
@override
|
||||
State<HomeScreen> createState() => _HomeScreenState();
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen>
|
||||
with TickerProviderStateMixin {
|
||||
// ----------------------------------------------------------------
|
||||
// ESTADO LOCAL
|
||||
// ----------------------------------------------------------------
|
||||
int? _usuarioId;
|
||||
ETAInfo? _etaInfo;
|
||||
bool _cargando = true;
|
||||
String? _error;
|
||||
|
||||
// Timer para auto-refresh cada 60 segundos
|
||||
Timer? _refreshTimer;
|
||||
|
||||
// Controlador de animación para el pulso del círculo de ETA
|
||||
late AnimationController _pulseController;
|
||||
late Animation<double> _pulseAnimation;
|
||||
|
||||
final ApiService _apiService = ApiService();
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// LIFECYCLE
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
// Configurar animación de pulso (escala entre 1.0 y 1.05)
|
||||
// Da vida a la UI y atrae atención al ETA — importante para demos
|
||||
_pulseController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 2),
|
||||
)..repeat(reverse: true);
|
||||
|
||||
_pulseAnimation = Tween<double>(begin: 1.0, end: 1.05).animate(
|
||||
CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
|
||||
);
|
||||
|
||||
// didChangeDependencies se llama después de initState y tiene
|
||||
// acceso al context (necesario para Navigator.arguments).
|
||||
// Por eso la carga de datos inicial va en didChangeDependencies.
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
|
||||
// Obtener el usuario_id pasado desde LoginScreen
|
||||
// Solo lo hacemos una vez (cuando _usuarioId aún es null)
|
||||
if (_usuarioId == null) {
|
||||
final args = ModalRoute.of(context)?.settings.arguments;
|
||||
if (args is int) {
|
||||
_usuarioId = args;
|
||||
_cargarETA();
|
||||
_iniciarAutoRefresh();
|
||||
// _registrarFCMToken(); // Activar cuando Firebase esté listo
|
||||
} else {
|
||||
// Fallback: leer de shared_preferences si no viene por argumento
|
||||
_cargarUsuarioDeStorage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pulseController.dispose();
|
||||
_refreshTimer?.cancel(); // MUY IMPORTANTE: cancelar timer para evitar leaks
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// CARGAR USUARIO ID DESDE STORAGE (fallback)
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _cargarUsuarioDeStorage() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final id = prefs.getInt('usuario_id');
|
||||
if (id != null) {
|
||||
setState(() => _usuarioId = id);
|
||||
_cargarETA();
|
||||
_iniciarAutoRefresh();
|
||||
} else {
|
||||
// No hay sesión, volver al login
|
||||
if (mounted) {
|
||||
Navigator.pushReplacementNamed(context, '/');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// CARGAR ETA DESDE EL BACKEND
|
||||
//
|
||||
// Centralizado aquí para poder llamarlo tanto en init como
|
||||
// en el auto-refresh y en el botón de recarga manual.
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _cargarETA() async {
|
||||
if (_usuarioId == null) return;
|
||||
|
||||
// Solo mostrar spinner en la carga inicial, no en refresh silencioso
|
||||
if (_etaInfo == null) {
|
||||
setState(() {
|
||||
_cargando = true;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
final eta = await _apiService.obtenerETA(_usuarioId!);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_etaInfo = eta;
|
||||
_cargando = false;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_cargando = false;
|
||||
_error = 'No se pudo conectar al servidor.\nVerifica que el backend esté corriendo.';
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// AUTO-REFRESH CADA 60 SEGUNDOS
|
||||
//
|
||||
// Simula que el ETA se actualiza en tiempo real sin que el
|
||||
// usuario tenga que hacer pull-to-refresh manualmente.
|
||||
// En producción: usar WebSockets o Server-Sent Events.
|
||||
// ----------------------------------------------------------------
|
||||
void _iniciarAutoRefresh() {
|
||||
_refreshTimer = Timer.periodic(
|
||||
const Duration(seconds: 60),
|
||||
(_) => _cargarETA(),
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// REGISTRAR FCM TOKEN EN EL BACKEND
|
||||
//
|
||||
// Obtiene el token único de este dispositivo de Firebase y lo
|
||||
// manda al backend para poder recibir notificaciones push.
|
||||
// DESCOMENTA cuando tengas Firebase configurado.
|
||||
// ----------------------------------------------------------------
|
||||
// Future<void> _registrarFCMToken() async {
|
||||
// try {
|
||||
// final messaging = FirebaseMessaging.instance;
|
||||
//
|
||||
// // Pedir permisos de notificación al usuario (iOS requiere esto)
|
||||
// final settings = await messaging.requestPermission(
|
||||
// alert: true,
|
||||
// sound: true,
|
||||
// badge: true,
|
||||
// );
|
||||
//
|
||||
// if (settings.authorizationStatus == AuthorizationStatus.authorized) {
|
||||
// final token = await messaging.getToken();
|
||||
// if (token != null && _usuarioId != null) {
|
||||
// await _apiService.registrarFcmToken(_usuarioId!, token);
|
||||
// debugPrint('✅ FCM Token registrado: ${token.substring(0, 20)}...');
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Escuchar notificaciones cuando la app está en FOREGROUND
|
||||
// FirebaseMessaging.onMessage.listen((RemoteMessage message) {
|
||||
// if (message.notification != null && mounted) {
|
||||
// ScaffoldMessenger.of(context).showSnackBar(
|
||||
// SnackBar(
|
||||
// content: Text('🚛 ${message.notification!.body}'),
|
||||
// backgroundColor: Colors.green.shade700,
|
||||
// duration: const Duration(seconds: 5),
|
||||
// ),
|
||||
// );
|
||||
// // Refrescar ETA al recibir notificación
|
||||
// _cargarETA();
|
||||
// }
|
||||
// });
|
||||
// } catch (e) {
|
||||
// debugPrint('Error registrando FCM token: $e');
|
||||
// }
|
||||
// }
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// CERRAR SESIÓN
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _cerrarSesion() async {
|
||||
_refreshTimer?.cancel();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.clear();
|
||||
if (mounted) {
|
||||
Navigator.pushReplacementNamed(context, '/');
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// HELPERS DE UI
|
||||
// ================================================================
|
||||
|
||||
// Determina el color del fondo según el ETA (urgencia visual)
|
||||
Color _colorSegunETA(int etaMinutos) {
|
||||
if (etaMinutos <= 5) return const Color(0xFFB71C1C); // Rojo: ¡URGENTE!
|
||||
if (etaMinutos <= 15) return const Color(0xFFF57F17); // Naranja: Pronto
|
||||
if (etaMinutos <= 30) return const Color(0xFF1B5E20); // Verde: Con tiempo
|
||||
return const Color(0xFF1A237E); // Azul: Tranquilo
|
||||
}
|
||||
|
||||
// Emoji indicador de urgencia
|
||||
String _emojiSegunETA(int etaMinutos) {
|
||||
if (etaMinutos <= 5) return '🔴';
|
||||
if (etaMinutos <= 15) return '🟡';
|
||||
if (etaMinutos <= 30) return '🟢';
|
||||
return '🔵';
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// BUILD PRINCIPAL
|
||||
// ================================================================
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 800),
|
||||
// El fondo cambia de color según la urgencia del ETA
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: _etaInfo != null
|
||||
? [
|
||||
_colorSegunETA(_etaInfo!.etaMinutos),
|
||||
_colorSegunETA(_etaInfo!.etaMinutos).withOpacity(0.7),
|
||||
]
|
||||
: [const Color(0xFF2E7D32), const Color(0xFF1B5E20)],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: _buildContenido(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContenido() {
|
||||
// Estado: Cargando
|
||||
if (_cargando) {
|
||||
return const Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
CircularProgressIndicator(color: Colors.white),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Consultando estado del camión...',
|
||||
style: TextStyle(color: Colors.white70, fontSize: 16),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Estado: Error
|
||||
if (_error != null) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.wifi_off_rounded, size: 80, color: Colors.white54),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
_error!,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 18),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
ElevatedButton.icon(
|
||||
onPressed: _cargarETA,
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Reintentar'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: Colors.red.shade700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Estado: Con datos - UI principal
|
||||
return _buildUIConDatos();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// UI PRINCIPAL CON DATOS DE ETA
|
||||
//
|
||||
// DECISIÓN DE DISEÑO: El mensaje preventivo ocupa 60% de la
|
||||
// pantalla porque es lo más importante. El usuario debe verlo
|
||||
// de un vistazo, sin lentes y desde lejos.
|
||||
// ----------------------------------------------------------------
|
||||
Widget _buildUIConDatos() {
|
||||
if (_etaInfo == null) return const SizedBox.shrink();
|
||||
final eta = _etaInfo!;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
// --------------------------------------------------------
|
||||
// HEADER: Barra superior con colonia y botón de logout
|
||||
// --------------------------------------------------------
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// Colonia del usuario
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.location_on, color: Colors.white70, size: 18),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
eta.colonia,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
// Botón de logout
|
||||
IconButton(
|
||||
onPressed: _cerrarSesion,
|
||||
icon: const Icon(Icons.logout, color: Colors.white70),
|
||||
tooltip: 'Cerrar sesión',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const Spacer(flex: 1),
|
||||
|
||||
// --------------------------------------------------------
|
||||
// CENTRO: ETA Visual (el corazón de la pantalla)
|
||||
// ScaleTransition aplica la animación de pulso al círculo
|
||||
// --------------------------------------------------------
|
||||
ScaleTransition(
|
||||
scale: _pulseAnimation,
|
||||
child: Container(
|
||||
width: 220,
|
||||
height: 220,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: Colors.white.withOpacity(0.15),
|
||||
border: Border.all(color: Colors.white, width: 3),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
_emojiSegunETA(eta.etaMinutos),
|
||||
style: const TextStyle(fontSize: 48),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// Número de minutos — el dato más importante
|
||||
Text(
|
||||
'${eta.etaMinutos}',
|
||||
style: const TextStyle(
|
||||
fontSize: 64,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: Colors.white,
|
||||
height: 1,
|
||||
),
|
||||
),
|
||||
const Text(
|
||||
'minutos',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
color: Colors.white70,
|
||||
fontWeight: FontWeight.w300,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// ETA en texto descriptivo
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32),
|
||||
child: Text(
|
||||
eta.etaTexto,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
fontSize: 22,
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// --------------------------------------------------------
|
||||
// MENSAJE PREVENTIVO — El núcleo del producto
|
||||
//
|
||||
// Este es el mensaje que el usuario DEBE leer. Enorme,
|
||||
// contrastado, en un card destacado. Sin distracciones.
|
||||
// --------------------------------------------------------
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20),
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(vertical: 28, horizontal: 24),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.2),
|
||||
blurRadius: 20,
|
||||
offset: const Offset(0, 8),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Text(
|
||||
// ¡ESTE ES EL MENSAJE PRINCIPAL DEL SISTEMA!
|
||||
// Viene del backend (campo mensaje_preventivo)
|
||||
// Ejemplos:
|
||||
// "⏰ Prepárate, el camión llega pronto. No saques tu basura aún."
|
||||
// "🚛 ¡El camión está muy cerca! Saca tu basura AHORA."
|
||||
eta.mensajePreventivo,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: _colorSegunETA(eta.etaMinutos),
|
||||
height: 1.3,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const Spacer(flex: 2),
|
||||
|
||||
// --------------------------------------------------------
|
||||
// FOOTER: Botón de refresh manual + última actualización
|
||||
// --------------------------------------------------------
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 32),
|
||||
child: Column(
|
||||
children: [
|
||||
// Indicador de auto-refresh
|
||||
const Text(
|
||||
'🔄 Se actualiza automáticamente cada minuto',
|
||||
style: TextStyle(color: Colors.white54, fontSize: 12),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
// Botón de refresh manual para demos / jueces impacientes
|
||||
OutlinedButton.icon(
|
||||
onPressed: _cargarETA,
|
||||
icon: const Icon(Icons.refresh, color: Colors.white),
|
||||
label: const Text(
|
||||
'Actualizar ahora',
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: const BorderSide(color: Colors.white54),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
357
aplicacion_hack/lib/screens/login_screen.dart
Normal file
357
aplicacion_hack/lib/screens/login_screen.dart
Normal file
@@ -0,0 +1,357 @@
|
||||
// ================================================================
|
||||
// lib/screens/login_screen.dart
|
||||
// Pantalla de Login Mockeada — Hackathon MVP
|
||||
// ================================================================
|
||||
//
|
||||
// PROPÓSITO:
|
||||
// Simular la selección de identidad de usuario para la demo.
|
||||
// En producción aquí iría: Google Sign-In, OTP por SMS, etc.
|
||||
//
|
||||
// FLUJO:
|
||||
// 1. Usuario ingresa un ID numérico (1-4 para los seed data)
|
||||
// 2. Selecciona su colonia en un Dropdown
|
||||
// 3. Presiona "Entrar" -> navega a HomeScreen con el usuario_id
|
||||
//
|
||||
// ATAJO DE HACKATHON:
|
||||
// El "ID de usuario" es manual para evitar un sistema de auth
|
||||
// completo. Para la demo, los IDs 1-4 son los del seed.
|
||||
// ================================================================
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../services/api_service.dart';
|
||||
|
||||
class LoginScreen extends StatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
State<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen> {
|
||||
// ----------------------------------------------------------------
|
||||
// ESTADO LOCAL
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
// Controlador para el TextField del ID de usuario
|
||||
final TextEditingController _idController = TextEditingController();
|
||||
|
||||
// Colonia seleccionada en el Dropdown (null = no seleccionada aún)
|
||||
String? _coloniaSeleccionada;
|
||||
|
||||
// Lista de colonias cargadas desde el backend
|
||||
List<String> _colonias = [];
|
||||
|
||||
// Estado de carga: mostramos spinner mientras cargamos colonias
|
||||
bool _cargandoColonias = true;
|
||||
|
||||
// Estado de error al cargar colonias
|
||||
String? _errorColonias;
|
||||
|
||||
// Estado del botón de login: evita doble tap
|
||||
bool _logueando = false;
|
||||
|
||||
// Servicio de API (instancia local, sin inyección para el hackathon)
|
||||
final ApiService _apiService = ApiService();
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// LIFECYCLE
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarColonias();
|
||||
_verificarSesionExistente();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Siempre liberar controllers para evitar memory leaks
|
||||
_idController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// VERIFICAR SESIÓN EXISTENTE
|
||||
//
|
||||
// Si el usuario ya se logueó antes (guardado en shared_preferences),
|
||||
// lo mandamos directo al home sin pasar por el login.
|
||||
// ATAJO: Esto simula "recordar sesión". No es auth real.
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _verificarSesionExistente() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final usuarioIdGuardado = prefs.getInt('usuario_id');
|
||||
|
||||
if (usuarioIdGuardado != null && mounted) {
|
||||
// Ya hay sesión, ir al home directamente
|
||||
Navigator.pushReplacementNamed(
|
||||
context,
|
||||
'/home',
|
||||
arguments: usuarioIdGuardado,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// CARGAR COLONIAS DESDE EL BACKEND
|
||||
//
|
||||
// Intenta cargar desde la API. Si falla (backend apagado),
|
||||
// usa una lista de fallback hardcodeada para no bloquear la demo.
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _cargarColonias() async {
|
||||
try {
|
||||
final colonias = await _apiService.obtenerColonias();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_colonias = colonias;
|
||||
_cargandoColonias = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// FALLBACK: Lista hardcodeada por si el backend no está corriendo
|
||||
// Útil para desarrollar el frontend en paralelo al backend
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_colonias = [
|
||||
'Zona Centro',
|
||||
'Col. Hidalgo',
|
||||
'Col. Independencia',
|
||||
'Col. Obrera',
|
||||
'Col. San Juan',
|
||||
'Fracc. Los Pinos',
|
||||
'Col. Reforma',
|
||||
];
|
||||
_cargandoColonias = false;
|
||||
_errorColonias = 'Sin conexión al backend. Usando lista local.';
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// ACCIÓN: INICIAR SESIÓN
|
||||
// Valida, guarda y navega.
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _iniciarSesion() async {
|
||||
// Validación básica del ID
|
||||
final idTexto = _idController.text.trim();
|
||||
if (idTexto.isEmpty) {
|
||||
_mostrarError('Por favor ingresa tu ID de usuario.');
|
||||
return;
|
||||
}
|
||||
|
||||
final usuarioId = int.tryParse(idTexto);
|
||||
if (usuarioId == null || usuarioId <= 0) {
|
||||
_mostrarError('El ID debe ser un número positivo (ej: 1, 2, 3, 4).');
|
||||
return;
|
||||
}
|
||||
|
||||
if (_coloniaSeleccionada == null) {
|
||||
_mostrarError('Por favor selecciona tu colonia.');
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() => _logueando = true);
|
||||
|
||||
// Guardar la sesión en shared_preferences para no pedir login de nuevo
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setInt('usuario_id', usuarioId);
|
||||
await prefs.setString('colonia', _coloniaSeleccionada!);
|
||||
|
||||
// Navegar a la pantalla principal pasando el usuario_id como argumento
|
||||
if (mounted) {
|
||||
Navigator.pushReplacementNamed(
|
||||
context,
|
||||
'/home',
|
||||
arguments: usuarioId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// HELPER: Mostrar mensaje de error con SnackBar
|
||||
// ----------------------------------------------------------------
|
||||
void _mostrarError(String mensaje) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(mensaje),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// UI
|
||||
// ================================================================
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: colorScheme.surface,
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// ------------------------------------------------
|
||||
// HEADER: Ícono y título
|
||||
// ------------------------------------------------
|
||||
Icon(
|
||||
Icons.recycling_rounded,
|
||||
size: 80,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Recolección\nInteligente',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Ingresa tus datos para recibir notificaciones de tu camión',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Colors.grey.shade600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 48),
|
||||
|
||||
// ------------------------------------------------
|
||||
// CAMPO: ID de Usuario
|
||||
// NOTA PARA EL EQUIPO: Para la demo usa IDs 1 al 4
|
||||
// (son los que creó el seed del backend)
|
||||
// ------------------------------------------------
|
||||
TextField(
|
||||
controller: _idController,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'ID de Usuario',
|
||||
hintText: 'Ej: 1, 2, 3 ó 4',
|
||||
helperText: 'Usa los IDs del seed del backend (1-4)',
|
||||
prefixIcon: const Icon(Icons.person_outline),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// ------------------------------------------------
|
||||
// DROPDOWN: Selección de Colonia
|
||||
// ------------------------------------------------
|
||||
if (_cargandoColonias)
|
||||
const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
// Aviso si se usó el fallback local
|
||||
if (_errorColonias != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(
|
||||
'⚠️ $_errorColonias',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.orange.shade700,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// El DropdownButtonFormField necesita que los items
|
||||
// vengan de _colonias, que se cargó en initState.
|
||||
DropdownButtonFormField<String>(
|
||||
value: _coloniaSeleccionada,
|
||||
hint: const Text('Selecciona tu colonia'),
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: const Icon(Icons.location_city_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
// Convierte cada String de _colonias en un DropdownMenuItem
|
||||
items: _colonias.map((colonia) {
|
||||
return DropdownMenuItem(
|
||||
value: colonia,
|
||||
child: Text(colonia),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (valor) {
|
||||
setState(() => _coloniaSeleccionada = valor);
|
||||
},
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// ------------------------------------------------
|
||||
// BOTÓN: Entrar
|
||||
// Muestra spinner mientras _logueando == true
|
||||
// ------------------------------------------------
|
||||
SizedBox(
|
||||
height: 56,
|
||||
child: ElevatedButton(
|
||||
onPressed: _logueando ? null : _iniciarSesion,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorScheme.primary,
|
||||
foregroundColor: colorScheme.onPrimary,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: _logueando
|
||||
? const SizedBox(
|
||||
height: 24,
|
||||
width: 24,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: const Text(
|
||||
'Entrar',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Nota informativa para jueces/demos
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.primaryContainer.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'🧪 Demo: Usa IDs del 1 al 4. Corre primero POST /api/seed en el backend.',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user