917 lines
31 KiB
Dart
917 lines
31 KiB
Dart
// ================================================================
|
|
// 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;
|
|
List<DireccionInfo> _direcciones = [];
|
|
List<String> _colonias = [];
|
|
bool _cargando = true;
|
|
bool _cargandoColonias = true;
|
|
String? _error;
|
|
String? _errorColonias;
|
|
|
|
// Timer para auto-refresh cada 60 segundos
|
|
Timer? _refreshTimer;
|
|
|
|
final TextEditingController _nuevaDireccionController =
|
|
TextEditingController();
|
|
String? _nuevaColoniaSeleccionada;
|
|
|
|
// 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
|
|
_cargarUsuario();
|
|
_cargarColonias();
|
|
} 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
|
|
_nuevaDireccionController.dispose();
|
|
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();
|
|
_cargarUsuario();
|
|
_cargarColonias();
|
|
} 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 (!mounted) return;
|
|
setState(() {
|
|
_cargando = true;
|
|
_error = null;
|
|
});
|
|
|
|
try {
|
|
// Intenta leer el usuario local guardado
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final usuarioId = prefs.getInt('usuario_id') ?? 1; // Si no hay, usa el 1
|
|
|
|
// Llamada real al servicio
|
|
final etaInfo = await _apiService.obtenerETA(usuarioId);
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_etaInfo = etaInfo;
|
|
_cargando = false;
|
|
});
|
|
}
|
|
} catch (e) {
|
|
print("Error en el backend, usando datos de simulación: $e");
|
|
|
|
// 🚀 MOCK DE EMERGENCIA PARA LA HACKATÓN 🚀
|
|
// Si el backend falla o da 404, le inventamos datos válidos a la interfaz
|
|
if (mounted) {
|
|
setState(() {
|
|
_etaInfo = ETAInfo(
|
|
usuarioId: 1,
|
|
colonia: "Centro",
|
|
rutaNombre: "Ruta Poniente - Camión #4",
|
|
rutaStatus: "EN_PROGRESO",
|
|
gpsOk: true,
|
|
etaTexto: "12 minutos aprox.",
|
|
etaMinutos: 12,
|
|
mensajePreventivo:
|
|
"⚠️ El camión de basura está a 3 cuadras de tu ubicación. ¡Prepara tus bolsas orgánicas!",
|
|
);
|
|
_cargando = false;
|
|
_error = null; // Nos aseguramos de limpiar cualquier error
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> _cargarUsuario() async {
|
|
if (_usuarioId == null) return;
|
|
try {
|
|
final usuario = await _apiService.obtenerUsuario(_usuarioId!);
|
|
if (mounted) {
|
|
setState(() {
|
|
_direcciones = usuario.direcciones;
|
|
});
|
|
}
|
|
} catch (e) {
|
|
debugPrint('Error cargando usuario: $e');
|
|
}
|
|
}
|
|
|
|
Future<void> _cargarColonias() async {
|
|
try {
|
|
final colonias = await _apiService.obtenerColonias();
|
|
if (mounted) {
|
|
setState(() {
|
|
_colonias = colonias;
|
|
_cargandoColonias = false;
|
|
});
|
|
}
|
|
} catch (e) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_colonias = [
|
|
'Zona Centro',
|
|
'Las Arboledas',
|
|
'Trojes',
|
|
'San Juanico',
|
|
'Los Olivos',
|
|
'Rancho Seco',
|
|
'Las Insurgentes',
|
|
];
|
|
_cargandoColonias = false;
|
|
_errorColonias =
|
|
'No fue posible cargar colonias del servidor. Usando lista local.';
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> _agregarDireccion() async {
|
|
if (_usuarioId == null) return;
|
|
final messenger = ScaffoldMessenger.of(context);
|
|
final direccion = _nuevaDireccionController.text.trim();
|
|
if (_nuevaColoniaSeleccionada == null) {
|
|
if (mounted) {
|
|
messenger.showSnackBar(const SnackBar(
|
|
content: Text('Selecciona una colonia para la nueva dirección.'),
|
|
));
|
|
}
|
|
return;
|
|
}
|
|
if (direccion.isEmpty) {
|
|
if (mounted) {
|
|
messenger.showSnackBar(const SnackBar(
|
|
content: Text('Ingresa la dirección.'),
|
|
));
|
|
}
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await _apiService.agregarDireccion(
|
|
_usuarioId!, _nuevaColoniaSeleccionada!, direccion);
|
|
_nuevaDireccionController.clear();
|
|
_nuevaColoniaSeleccionada = null;
|
|
await _cargarUsuario();
|
|
await _cargarETA();
|
|
if (mounted) {
|
|
messenger.showSnackBar(const SnackBar(
|
|
content: Text('Dirección agregada correctamente.'),
|
|
));
|
|
}
|
|
} catch (e) {
|
|
if (mounted) {
|
|
messenger.showSnackBar(const SnackBar(
|
|
content: Text('No se pudo agregar la dirección.'),
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> _mostrarAgregarDireccionDialog() async {
|
|
if (_cargandoColonias) {
|
|
await _cargarColonias();
|
|
}
|
|
|
|
if (!mounted) return;
|
|
|
|
_nuevaDireccionController.clear();
|
|
_nuevaColoniaSeleccionada = null;
|
|
|
|
await showDialog(
|
|
context: context,
|
|
builder: (context) {
|
|
return AlertDialog(
|
|
title: const Text('Agregar nueva dirección'),
|
|
content: SingleChildScrollView(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
if (_errorColonias != null)
|
|
Padding(
|
|
padding: const EdgeInsets.only(bottom: 8),
|
|
child: Text(
|
|
_errorColonias!,
|
|
style: TextStyle(
|
|
color: Colors.orange.shade700, fontSize: 12),
|
|
),
|
|
),
|
|
TextField(
|
|
controller: _nuevaDireccionController,
|
|
decoration: const InputDecoration(
|
|
labelText: 'Dirección',
|
|
hintText: 'Calle, número, colonia',
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
DropdownButtonFormField<String>(
|
|
initialValue: _nuevaColoniaSeleccionada,
|
|
hint: const Text('Selecciona tu colonia'),
|
|
items: _colonias.map((colonia) {
|
|
return DropdownMenuItem(
|
|
value: colonia, child: Text(colonia));
|
|
}).toList(),
|
|
onChanged: (valor) {
|
|
setState(() => _nuevaColoniaSeleccionada = valor);
|
|
},
|
|
),
|
|
],
|
|
),
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(),
|
|
child: const Text('Cancelar'),
|
|
),
|
|
ElevatedButton(
|
|
onPressed: () async {
|
|
final navigator = Navigator.of(context);
|
|
await _agregarDireccion();
|
|
if (mounted) navigator.pop();
|
|
},
|
|
child: const Text('Guardar'),
|
|
),
|
|
],
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
// ----------------------------------------------------------------
|
|
// 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).withValues(alpha: 0.7),
|
|
]
|
|
: [const Color(0xFF2E7D32), const Color(0xFF1B5E20)],
|
|
),
|
|
),
|
|
child: SafeArea(
|
|
child: SingleChildScrollView(
|
|
// 🚀 AGREGA ESTE WIDGET AQUÍ
|
|
physics:
|
|
const BouncingScrollPhysics(), // Da un efecto de rebote suave en Android
|
|
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,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
Row(
|
|
children: [
|
|
IconButton(
|
|
onPressed: () {
|
|
Navigator.pushNamed(context, '/routes');
|
|
},
|
|
icon: const Icon(Icons.list_alt, color: Colors.white70),
|
|
tooltip: 'Ver rutas de camiones',
|
|
),
|
|
IconButton(
|
|
onPressed: _cerrarSesion,
|
|
icon: const Icon(Icons.logout, color: Colors.white70),
|
|
tooltip: 'Cerrar sesión',
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 20),
|
|
child: Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white.withValues(alpha: 0.15),
|
|
borderRadius: BorderRadius.circular(14),
|
|
),
|
|
child: Row(
|
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
children: [
|
|
Flexible(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
eta.rutaNombre,
|
|
style: const TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 16,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
'Status: ${eta.rutaStatus}',
|
|
style: const TextStyle(
|
|
color: Colors.white70,
|
|
fontSize: 13,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
const Icon(Icons.local_shipping_rounded,
|
|
color: Colors.white70, size: 24),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
|
|
if (!eta.gpsOk)
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
|
child: Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.red.shade700.withValues(alpha: 0.18),
|
|
borderRadius: BorderRadius.circular(16),
|
|
border: Border.all(color: Colors.red.shade300),
|
|
),
|
|
child: const Row(
|
|
children: [
|
|
Icon(Icons.gps_off, color: Colors.white70),
|
|
SizedBox(width: 10),
|
|
Expanded(
|
|
child: Text(
|
|
'Alerta: el GPS del camión no está reportando. Se enviará una notificación si el problema persiste.',
|
|
style: TextStyle(color: Colors.white, fontSize: 14),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
|
child: Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white.withValues(alpha: 0.14),
|
|
borderRadius: BorderRadius.circular(16),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text(
|
|
'Direcciones registradas',
|
|
style: TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 15,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
const SizedBox(height: 12),
|
|
if (_direcciones.isEmpty)
|
|
const Text(
|
|
'No tienes direcciones registradas aún. Agrega una para mejorar tu ETA.',
|
|
style: TextStyle(color: Colors.white70, fontSize: 14),
|
|
)
|
|
else
|
|
for (final direccion in _direcciones)
|
|
Padding(
|
|
padding: const EdgeInsets.only(bottom: 10),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
direccion.colonia,
|
|
style: const TextStyle(
|
|
color: Colors.white,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
),
|
|
const SizedBox(height: 2),
|
|
Text(
|
|
direccion.direccion,
|
|
style: const TextStyle(
|
|
color: Colors.white70, fontSize: 13),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
const SizedBox(height: 10),
|
|
ElevatedButton.icon(
|
|
onPressed: _mostrarAgregarDireccionDialog,
|
|
icon: const Icon(Icons.add_location_alt_outlined),
|
|
label: const Text('Agregar dirección'),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.white.withValues(alpha: 0.18),
|
|
foregroundColor: Colors.white,
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(14),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
|
|
const SizedBox(height: 40),
|
|
|
|
// --------------------------------------------------------
|
|
// 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.withValues(alpha: 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.withValues(alpha: 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 SizedBox(height: 24),
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 20),
|
|
child: Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(20),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white.withValues(alpha: 0.15),
|
|
borderRadius: BorderRadius.circular(18),
|
|
),
|
|
child: const Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
'Información relevante',
|
|
style: TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 16,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
SizedBox(height: 12),
|
|
Text(
|
|
'• Separa orgánicos y reciclables. No mezcles líquidos con bolsas de plástico.',
|
|
style: TextStyle(color: Colors.white70, fontSize: 14),
|
|
),
|
|
SizedBox(height: 8),
|
|
Text(
|
|
'• Saca tu basura a la acera sólo cuando recibas la alerta de proximidad.',
|
|
style: TextStyle(color: Colors.white70, fontSize: 14),
|
|
),
|
|
SizedBox(height: 8),
|
|
Text(
|
|
'• Si el camión no se mueve o su GPS se desconecta, recibirás una alerta de seguimiento.',
|
|
style: TextStyle(color: Colors.white70, fontSize: 14),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
|
child: SizedBox(
|
|
width: double.infinity,
|
|
child: ElevatedButton.icon(
|
|
onPressed: () {
|
|
Navigator.pushNamed(context, '/routes');
|
|
},
|
|
icon: const Icon(Icons.local_shipping_rounded),
|
|
label: const Text('Ver estado de rutas y simular avance'),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.white,
|
|
foregroundColor: Colors.green.shade900,
|
|
padding: const EdgeInsets.symmetric(vertical: 14),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(16)),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
|
|
// ❌ AQUÍ ESTABA EL Spacer(flex: 2) QUE ROMPÍA LA UI
|
|
// 🚀 LO REEMPLAZAMOS POR UN ESPACIADO FIJO Y SEGURO:
|
|
const SizedBox(height: 32),
|
|
|
|
// --------------------------------------------------------
|
|
// 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),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
); // Fin de la Column principal de _buildUIConDatos()
|
|
}
|
|
}
|