feat: added map merge with supabase structure
This commit is contained in:
@@ -1,78 +0,0 @@
|
||||
// lib/core/theme/app_theme.dart
|
||||
// Persona C importa este archivo también.
|
||||
// Un solo lugar para colores, tipografía y estilos.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppTheme {
|
||||
AppTheme._();
|
||||
|
||||
// ── Paleta de categorías ─────────────────────────────────────────
|
||||
static const organicosColor = Color(0xFF4CAF50);
|
||||
static const reciclabledColor = Color(0xFF2196F3);
|
||||
static const sanitariosColor = Color(0xFFFF5722);
|
||||
static const especialesColor = Color(0xFFFF9800);
|
||||
|
||||
// ── Paleta general ───────────────────────────────────────────────
|
||||
static const primaryColor = Color(0xFF1B5E20); // verde oscuro
|
||||
static const secondaryColor = Color(0xFF2E7D32);
|
||||
static const backgroundColor = Color(0xFFF5F5F5);
|
||||
static const surfaceColor = Color(0xFFFFFFFF);
|
||||
static const errorColor = Color(0xFFD32F2F);
|
||||
|
||||
static ThemeData get lightTheme => ThemeData(
|
||||
useMaterial3: true,
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: primaryColor,
|
||||
surface: surfaceColor,
|
||||
error: errorColor,
|
||||
),
|
||||
scaffoldBackgroundColor: backgroundColor,
|
||||
appBarTheme: const AppBarTheme(
|
||||
backgroundColor: primaryColor,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
centerTitle: true,
|
||||
titleTextStyle: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
cardTheme: CardTheme(
|
||||
color: surfaceColor,
|
||||
elevation: 2,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
chipTheme: ChipThemeData(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: surfaceColor,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// ── Colores por id de categoría ──────────────────────────────────
|
||||
static Color colorDeCategoriaId(String id) {
|
||||
return switch (id) {
|
||||
'organicos' => organicosColor,
|
||||
'reciclables' => reciclabledColor,
|
||||
'sanitarios' => sanitariosColor,
|
||||
'especiales' => especialesColor,
|
||||
_ => primaryColor,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// lib/features/recycling_guide/data/datasources/recycling_local_datasource.dart
|
||||
// Único archivo que sabe que los datos vienen de un JSON en assets.
|
||||
// Funciona sin conexión a internet.
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/services.dart';
|
||||
import '../../domain/entities/recycling_category.dart';
|
||||
|
||||
class RecyclingLocalDatasource {
|
||||
static const _assetPath = 'assets/recycling_guide.json';
|
||||
|
||||
// Cache en memoria — se carga una sola vez durante la sesión
|
||||
List<RecyclingCategory>? _cache;
|
||||
|
||||
Future<List<RecyclingCategory>> cargarCategorias() async {
|
||||
if (_cache != null) return _cache!;
|
||||
|
||||
final raw = await rootBundle.loadString(_assetPath);
|
||||
final List<dynamic> json = jsonDecode(raw);
|
||||
|
||||
_cache = json.map(_mapearCategoria).toList();
|
||||
return _cache!;
|
||||
}
|
||||
|
||||
RecyclingCategory _mapearCategoria(dynamic json) {
|
||||
final items = (json['items'] as List)
|
||||
.map(
|
||||
(i) => RecyclingItem(
|
||||
nombre: i['nombre'] as String,
|
||||
ejemplos: i['ejemplos'] as String,
|
||||
acepta: i['acepta'] as bool,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
|
||||
return RecyclingCategory(
|
||||
id: json['id'] as String,
|
||||
nombre: json['nombre'] as String,
|
||||
descripcion: json['descripcion'] as String,
|
||||
colorHex: json['color'] as String,
|
||||
icono: json['icono'] as String,
|
||||
consejo: json['consejo'] as String,
|
||||
items: items,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// lib/features/recycling_guide/data/repositories/recycling_repository.dart
|
||||
|
||||
import '../datasources/recycling_local_datasource.dart';
|
||||
import '../../domain/entities/recycling_category.dart';
|
||||
|
||||
class RecyclingRepository {
|
||||
final RecyclingLocalDatasource _datasource;
|
||||
|
||||
RecyclingRepository({RecyclingLocalDatasource? datasource})
|
||||
: _datasource = datasource ?? RecyclingLocalDatasource();
|
||||
|
||||
Future<List<RecyclingCategory>> obtenerCategorias() =>
|
||||
_datasource.cargarCategorias();
|
||||
|
||||
/// Busca en nombres y ejemplos de todos los items de todas las categorías.
|
||||
/// Devuelve pares (categoría, item) para que la UI sepa dónde mostrar el resultado.
|
||||
Future<List<SearchResult>> buscar(String query) async {
|
||||
if (query.trim().isEmpty) return [];
|
||||
|
||||
final q = query.toLowerCase();
|
||||
final categorias = await obtenerCategorias();
|
||||
final resultados = <SearchResult>[];
|
||||
|
||||
for (final cat in categorias) {
|
||||
for (final item in cat.items) {
|
||||
final coincide = item.nombre.toLowerCase().contains(q) ||
|
||||
item.ejemplos.toLowerCase().contains(q);
|
||||
if (coincide) {
|
||||
resultados.add(SearchResult(categoria: cat, item: item));
|
||||
}
|
||||
}
|
||||
}
|
||||
return resultados;
|
||||
}
|
||||
}
|
||||
|
||||
class SearchResult {
|
||||
final RecyclingCategory categoria;
|
||||
final RecyclingItem item;
|
||||
|
||||
const SearchResult({required this.categoria, required this.item});
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// lib/features/recycling_guide/domain/entities/recycling_category.dart
|
||||
// Capa de dominio — cero dependencias de Flutter o paquetes externos.
|
||||
|
||||
class RecyclingItem {
|
||||
final String nombre;
|
||||
final String ejemplos;
|
||||
final bool acepta; // true = sí va aquí, false = NO va aquí
|
||||
|
||||
const RecyclingItem({
|
||||
required this.nombre,
|
||||
required this.ejemplos,
|
||||
required this.acepta,
|
||||
});
|
||||
}
|
||||
|
||||
class RecyclingCategory {
|
||||
final String id;
|
||||
final String nombre;
|
||||
final String descripcion;
|
||||
final String colorHex;
|
||||
final String icono;
|
||||
final String consejo;
|
||||
final List<RecyclingItem> items;
|
||||
|
||||
const RecyclingCategory({
|
||||
required this.id,
|
||||
required this.nombre,
|
||||
required this.descripcion,
|
||||
required this.colorHex,
|
||||
required this.icono,
|
||||
required this.consejo,
|
||||
required this.items,
|
||||
});
|
||||
|
||||
/// Items que SÍ van en esta categoría
|
||||
List<RecyclingItem> get itemsAceptados =>
|
||||
items.where((i) => i.acepta).toList();
|
||||
|
||||
/// Items que NO van en esta categoría
|
||||
List<RecyclingItem> get itemsRechazados =>
|
||||
items.where((i) => !i.acepta).toList();
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
// lib/features/recycling_guide/presentation/providers/recycling_provider.dart
|
||||
// Riverpod — compatible con lo que usa Persona C en el resto de la app.
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../data/repositories/recycling_repository.dart';
|
||||
import '../../domain/entities/recycling_category.dart';
|
||||
|
||||
// ── Repositorio singleton ────────────────────────────────────────────
|
||||
final recyclingRepositoryProvider = Provider<RecyclingRepository>(
|
||||
(ref) => RecyclingRepository(),
|
||||
);
|
||||
|
||||
// ── Categorías (carga inicial desde JSON) ────────────────────────────
|
||||
final recyclingCategoriesProvider =
|
||||
FutureProvider<List<RecyclingCategory>>((ref) {
|
||||
return ref.watch(recyclingRepositoryProvider).obtenerCategorias();
|
||||
});
|
||||
|
||||
// ── Estado del buscador ──────────────────────────────────────────────
|
||||
class RecyclingSearchNotifier extends StateNotifier<RecyclingSearchState> {
|
||||
final RecyclingRepository _repo;
|
||||
|
||||
RecyclingSearchNotifier(this._repo)
|
||||
: super(const RecyclingSearchState.idle());
|
||||
|
||||
Future<void> buscar(String query) async {
|
||||
if (query.trim().isEmpty) {
|
||||
state = const RecyclingSearchState.idle();
|
||||
return;
|
||||
}
|
||||
state = const RecyclingSearchState.loading();
|
||||
final resultados = await _repo.buscar(query);
|
||||
state = RecyclingSearchState.done(resultados);
|
||||
}
|
||||
|
||||
void limpiar() => state = const RecyclingSearchState.idle();
|
||||
}
|
||||
|
||||
final recyclingSearchProvider =
|
||||
StateNotifierProvider<RecyclingSearchNotifier, RecyclingSearchState>((ref) {
|
||||
return RecyclingSearchNotifier(ref.watch(recyclingRepositoryProvider));
|
||||
});
|
||||
|
||||
// ── Estado sellado del buscador ──────────────────────────────────────
|
||||
sealed class RecyclingSearchState {
|
||||
const RecyclingSearchState();
|
||||
|
||||
const factory RecyclingSearchState.idle() = _Idle;
|
||||
const factory RecyclingSearchState.loading() = _Loading;
|
||||
const factory RecyclingSearchState.done(List<SearchResult> results) = _Done;
|
||||
}
|
||||
|
||||
class _Idle extends RecyclingSearchState {
|
||||
const _Idle();
|
||||
}
|
||||
|
||||
class _Loading extends RecyclingSearchState {
|
||||
const _Loading();
|
||||
}
|
||||
|
||||
class _Done extends RecyclingSearchState {
|
||||
final List<SearchResult> results;
|
||||
const _Done(this.results);
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
// lib/features/recycling_guide/presentation/screens/category_detail_screen.dart
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../domain/entities/recycling_category.dart';
|
||||
|
||||
class CategoryDetailScreen extends StatelessWidget {
|
||||
final RecyclingCategory categoria;
|
||||
|
||||
const CategoryDetailScreen({super.key, required this.categoria});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _parseColor(categoria.colorHex);
|
||||
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
// ── Header expandible ──────────────────────────────────
|
||||
SliverAppBar(
|
||||
expandedHeight: 180,
|
||||
pinned: true,
|
||||
backgroundColor: color,
|
||||
flexibleSpace: FlexibleSpaceBar(
|
||||
title: Text(
|
||||
categoria.nombre,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
background: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [color, color.withOpacity(0.7)],
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Icon(
|
||||
_iconoDesdeNombre(categoria.icono),
|
||||
size: 80,
|
||||
color: Colors.white.withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Descripción
|
||||
Text(
|
||||
categoria.descripcion,
|
||||
style: TextStyle(fontSize: 15, color: Colors.grey[700]),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Consejo destacado
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: color.withOpacity(0.3)),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.tips_and_updates, color: color, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
categoria.consejo,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: color,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Sección: SÍ van aquí
|
||||
if (categoria.itemsAceptados.isNotEmpty) ...[
|
||||
_SectionHeader(
|
||||
label: 'Sí van aquí',
|
||||
icon: Icons.check_circle,
|
||||
color: Colors.green,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
...categoria.itemsAceptados.map(
|
||||
(item) => _ItemTile(item: item, acepta: true),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
|
||||
// Sección: NO van aquí
|
||||
if (categoria.itemsRechazados.isNotEmpty) ...[
|
||||
_SectionHeader(
|
||||
label: 'No van aquí',
|
||||
icon: Icons.cancel,
|
||||
color: Colors.red,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
...categoria.itemsRechazados.map(
|
||||
(item) => _ItemTile(item: item, acepta: false),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _parseColor(String hex) {
|
||||
final h = hex.replaceFirst('#', '');
|
||||
return Color(int.parse('FF$h', radix: 16));
|
||||
}
|
||||
|
||||
IconData _iconoDesdeNombre(String nombre) {
|
||||
return switch (nombre) {
|
||||
'eco' => Icons.eco,
|
||||
'recycling' => Icons.recycling,
|
||||
'masks' => Icons.masks,
|
||||
'warning_amber' => Icons.warning_amber,
|
||||
_ => Icons.category,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionHeader extends StatelessWidget {
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
|
||||
const _SectionHeader({
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
children: [
|
||||
Icon(icon, color: color, size: 18),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ItemTile extends StatelessWidget {
|
||||
final RecyclingItem item;
|
||||
final bool acepta;
|
||||
|
||||
const _ItemTile({required this.item, required this.acepta});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
acepta ? Icons.check : Icons.close,
|
||||
size: 16,
|
||||
color: acepta ? Colors.green : Colors.red,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.nombre,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
item.ejemplos,
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
// lib/features/recycling_guide/presentation/screens/recycling_guide_screen.dart
|
||||
// Pantalla principal — Persona C la agrega al router así:
|
||||
// GoRoute(path: '/guia', builder: (_, __) => const RecyclingGuideScreen())
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../providers/recycling_provider.dart';
|
||||
import '../widgets/category_card.dart';
|
||||
import '../widgets/search_result_tile.dart';
|
||||
import 'category_detail_screen.dart';
|
||||
|
||||
class RecyclingGuideScreen extends ConsumerStatefulWidget {
|
||||
const RecyclingGuideScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<RecyclingGuideScreen> createState() =>
|
||||
_RecyclingGuideScreenState();
|
||||
}
|
||||
|
||||
class _RecyclingGuideScreenState extends ConsumerState<RecyclingGuideScreen> {
|
||||
final _searchCtrl = TextEditingController();
|
||||
bool _buscando = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onSearchChanged(String query) {
|
||||
setState(() => _buscando = query.trim().isNotEmpty);
|
||||
ref.read(recyclingSearchProvider.notifier).buscar(query);
|
||||
}
|
||||
|
||||
void _limpiarBusqueda() {
|
||||
_searchCtrl.clear();
|
||||
setState(() => _buscando = false);
|
||||
ref.read(recyclingSearchProvider.notifier).limpiar();
|
||||
FocusScope.of(context).unfocus();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Guía de separación'),
|
||||
actions: [
|
||||
// Badge offline — refuerza que funciona sin internet
|
||||
Container(
|
||||
margin: const EdgeInsets.only(right: 12),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.offline_bolt, size: 14, color: Colors.white),
|
||||
SizedBox(width: 4),
|
||||
Text(
|
||||
'sin internet',
|
||||
style: TextStyle(fontSize: 11, color: Colors.white),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// ── Buscador ────────────────────────────────────────────
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: TextField(
|
||||
controller: _searchCtrl,
|
||||
onChanged: _onSearchChanged,
|
||||
decoration: InputDecoration(
|
||||
hintText: '¿Dónde va el aceite? ¿y la pila?',
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: _buscando
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: _limpiarBusqueda,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// ── Contenido dinámico ──────────────────────────────────
|
||||
Expanded(
|
||||
child: _buscando
|
||||
? _SearchResults()
|
||||
: _CategoryList(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Lista de categorías ──────────────────────────────────────────────
|
||||
|
||||
class _CategoryList extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final async = ref.watch(recyclingCategoriesProvider);
|
||||
|
||||
return async.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (e, _) => Center(child: Text('Error: $e')),
|
||||
data: (categorias) => ListView.separated(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
|
||||
itemCount: categorias.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 12),
|
||||
itemBuilder: (context, i) => CategoryCard(
|
||||
categoria: categorias[i],
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) =>
|
||||
CategoryDetailScreen(categoria: categorias[i]),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Resultados de búsqueda ───────────────────────────────────────────
|
||||
|
||||
class _SearchResults extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final estado = ref.watch(recyclingSearchProvider);
|
||||
|
||||
return switch (estado) {
|
||||
_Idle() => const SizedBox.shrink(),
|
||||
_Loading() => const Center(child: CircularProgressIndicator()),
|
||||
_Done(results: final r) when r.isEmpty => Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.search_off, size: 48, color: Colors.grey[400]),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'No encontramos ese residuo.',
|
||||
style: TextStyle(color: Colors.grey[600]),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
_Done(results: final r) => ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: r.length,
|
||||
itemBuilder: (_, i) => SearchResultTile(resultado: r[i]),
|
||||
),
|
||||
_ => const SizedBox.shrink(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
// lib/features/recycling_guide/presentation/widgets/category_card.dart
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../domain/entities/recycling_category.dart';
|
||||
|
||||
class CategoryCard extends StatelessWidget {
|
||||
final RecyclingCategory categoria;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const CategoryCard({
|
||||
super.key,
|
||||
required this.categoria,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _parseColor(categoria.colorHex);
|
||||
|
||||
return Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
// Ícono con fondo coloreado
|
||||
Container(
|
||||
width: 56,
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(
|
||||
_iconoDesdeNombre(categoria.icono),
|
||||
color: color,
|
||||
size: 28,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// Texto
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
categoria.nombre,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
categoria.descripcion,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// Chip contador de items
|
||||
Row(
|
||||
children: [
|
||||
_CountChip(
|
||||
count: categoria.itemsAceptados.length,
|
||||
label: 'van aquí',
|
||||
color: Colors.green,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_CountChip(
|
||||
count: categoria.itemsRechazados.length,
|
||||
label: 'no van',
|
||||
color: Colors.red,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Icon(Icons.chevron_right, color: Colors.grey[400]),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _parseColor(String hex) {
|
||||
final h = hex.replaceFirst('#', '');
|
||||
return Color(int.parse('FF$h', radix: 16));
|
||||
}
|
||||
|
||||
IconData _iconoDesdeNombre(String nombre) {
|
||||
return switch (nombre) {
|
||||
'eco' => Icons.eco,
|
||||
'recycling' => Icons.recycling,
|
||||
'masks' => Icons.masks,
|
||||
'warning_amber'=> Icons.warning_amber,
|
||||
_ => Icons.category,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class _CountChip extends StatelessWidget {
|
||||
final int count;
|
||||
final String label;
|
||||
final Color color;
|
||||
|
||||
const _CountChip({
|
||||
required this.count,
|
||||
required this.label,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
'$count $label',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: color,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// lib/features/recycling_guide/presentation/widgets/search_result_tile.dart
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../data/repositories/recycling_repository.dart';
|
||||
|
||||
class SearchResultTile extends StatelessWidget {
|
||||
final SearchResult resultado;
|
||||
|
||||
const SearchResultTile({super.key, required this.resultado});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _parseColor(resultado.categoria.colorHex);
|
||||
final acepta = resultado.item.acepta;
|
||||
|
||||
return ListTile(
|
||||
leading: Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
acepta ? Icons.check_circle : Icons.cancel,
|
||||
color: acepta ? Colors.green : Colors.red,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
resultado.item.nombre,
|
||||
style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 14),
|
||||
),
|
||||
subtitle: Text(
|
||||
resultado.item.ejemplos,
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
|
||||
),
|
||||
trailing: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
resultado.categoria.nombre,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: color,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _parseColor(String hex) {
|
||||
final h = hex.replaceFirst('#', '');
|
||||
return Color(int.parse('FF$h', radix: 16));
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// lib/features/routes/data/datasources/routes_local_datasource.dart
|
||||
// Lee rutas.json desde assets — funciona completamente offline.
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/services.dart';
|
||||
import '../../domain/entities/route_entities.dart';
|
||||
import '../../domain/entities/haversine.dart';
|
||||
|
||||
class RoutesLocalDatasource {
|
||||
static const _assetPath = 'assets/rutas.json';
|
||||
|
||||
List<TruckRoute>? _cache;
|
||||
|
||||
Future<List<TruckRoute>> cargarRutas() async {
|
||||
if (_cache != null) return _cache!;
|
||||
|
||||
final raw = await rootBundle.loadString(_assetPath);
|
||||
final List<dynamic> json = jsonDecode(raw);
|
||||
|
||||
_cache = json.map((r) => TruckRoute.fromJson(r)).toList();
|
||||
return _cache!;
|
||||
}
|
||||
|
||||
/// Genera centroides de todas las rutas para búsqueda espacial con Haversine.
|
||||
Future<List<RouteCentroid>> generarCentroides() async {
|
||||
final rutas = await cargarRutas();
|
||||
return rutas.map(_calcularCentroide).toList();
|
||||
}
|
||||
|
||||
RouteCentroid _calcularCentroide(TruckRoute ruta) {
|
||||
// Excluye la última posición (regreso al depósito)
|
||||
final posiciones = ruta.positions.sublist(0, ruta.positions.length - 1);
|
||||
|
||||
final avgLat =
|
||||
posiciones.map((p) => p.lat).reduce((a, b) => a + b) / posiciones.length;
|
||||
final avgLng =
|
||||
posiciones.map((p) => p.lng).reduce((a, b) => a + b) / posiciones.length;
|
||||
|
||||
return RouteCentroid(
|
||||
routeId: ruta.routeId,
|
||||
routeName: ruta.name,
|
||||
centroidLat: avgLat,
|
||||
centroidLng: avgLng,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
// lib/features/routes/data/repositories/routes_repository.dart
|
||||
|
||||
import '../datasources/routes_local_datasource.dart';
|
||||
import '../../domain/entities/route_entities.dart';
|
||||
import '../../domain/entities/haversine.dart';
|
||||
|
||||
class RoutesRepository {
|
||||
final RoutesLocalDatasource _datasource;
|
||||
|
||||
RoutesRepository({RoutesLocalDatasource? datasource})
|
||||
: _datasource = datasource ?? RoutesLocalDatasource();
|
||||
|
||||
/// Obtiene todas las rutas disponibles
|
||||
Future<List<TruckRoute>> obtenerRutas() => _datasource.cargarRutas();
|
||||
|
||||
/// Obtiene una ruta por su ID
|
||||
Future<TruckRoute?> obtenerRutaPorId(String routeId) async {
|
||||
final rutas = await obtenerRutas();
|
||||
try {
|
||||
return rutas.firstWhere((r) => r.routeId == routeId);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Asigna la ruta más cercana a un domicilio usando Haversine.
|
||||
/// Cero Google Maps — motor espacial propio.
|
||||
Future<RouteAssignmentResult> asignarRuta(
|
||||
double userLat,
|
||||
double userLng,
|
||||
) async {
|
||||
final centroides = await _datasource.generarCentroides();
|
||||
return Haversine.findNearestRoute(userLat, userLng, centroides);
|
||||
}
|
||||
|
||||
/// Calcula ETA en minutos desde la posición actual del camión
|
||||
/// hasta el punto más cercano al domicilio del usuario.
|
||||
Future<ETAResult> calcularETA(
|
||||
String routeId,
|
||||
double userLat,
|
||||
double userLng,
|
||||
) async {
|
||||
final ruta = await obtenerRutaPorId(routeId);
|
||||
if (ruta == null) throw Exception('Ruta $routeId no encontrada');
|
||||
|
||||
// Encontrar posición más cercana al usuario en la ruta
|
||||
double minDist = double.infinity;
|
||||
int nearestIndex = 0;
|
||||
|
||||
for (int i = 0; i < ruta.positions.length - 1; i++) {
|
||||
final pos = ruta.positions[i];
|
||||
final d = Haversine.distanceKm(userLat, userLng, pos.lat, pos.lng);
|
||||
if (d < minDist) {
|
||||
minDist = d;
|
||||
nearestIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
final posicionCercana = ruta.positions[nearestIndex];
|
||||
final ahora = DateTime.now();
|
||||
|
||||
// Simular cuándo llegará el camión a esa posición
|
||||
final horaLlegada = posicionCercana.timestamp;
|
||||
final etaMinutos = horaLlegada.difference(ahora).inMinutes;
|
||||
|
||||
return ETAResult(
|
||||
routeId: routeId,
|
||||
routeName: ruta.name,
|
||||
etaMinutos: etaMinutos.clamp(0, 999),
|
||||
distanciaKm: minDist,
|
||||
posicionActual: posicionCercana,
|
||||
ventanaInicio: _formatHora(horaLlegada),
|
||||
ventanaFin: _formatHora(horaLlegada.add(const Duration(minutes: 15))),
|
||||
);
|
||||
}
|
||||
|
||||
String _formatHora(DateTime dt) {
|
||||
final hora = dt.hour > 12 ? dt.hour - 12 : dt.hour;
|
||||
final minutos = dt.minute.toString().padLeft(2, '0');
|
||||
final periodo = dt.hour >= 12 ? 'pm' : 'am';
|
||||
return '$hora:$minutos $periodo';
|
||||
}
|
||||
}
|
||||
|
||||
class ETAResult {
|
||||
final String routeId;
|
||||
final String routeName;
|
||||
final int etaMinutos;
|
||||
final double distanciaKm;
|
||||
final RoutePosition posicionActual;
|
||||
final String ventanaInicio;
|
||||
final String ventanaFin;
|
||||
|
||||
const ETAResult({
|
||||
required this.routeId,
|
||||
required this.routeName,
|
||||
required this.etaMinutos,
|
||||
required this.distanciaKm,
|
||||
required this.posicionActual,
|
||||
required this.ventanaInicio,
|
||||
required this.ventanaFin,
|
||||
});
|
||||
|
||||
String get ventana => '$ventanaInicio – $ventanaFin';
|
||||
|
||||
String get mensaje {
|
||||
if (etaMinutos <= 0) return 'El camión está pasando ahora. ¡Saca tu basura!';
|
||||
if (etaMinutos <= 10) return 'El camión llega en ~$etaMinutos min. ¡Saca tu basura!';
|
||||
return 'El camión llega entre $ventana.';
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// lib/features/routes/domain/entities/haversine.dart
|
||||
// Motor espacial propio — cero costo, funciona 100% offline.
|
||||
// Los jueces amarán esto.
|
||||
|
||||
import 'dart:math' show cos, sqrt, asin, pi;
|
||||
|
||||
class Haversine {
|
||||
Haversine._();
|
||||
|
||||
static const double _earthRadiusKm = 6371.0;
|
||||
|
||||
/// Distancia en kilómetros entre dos coordenadas geográficas.
|
||||
/// Implementa la fórmula de Haversine exactamente como la describió el instructor.
|
||||
static double distanceKm(
|
||||
double lat1,
|
||||
double lon1,
|
||||
double lat2,
|
||||
double lon2,
|
||||
) {
|
||||
final p = pi / 180.0;
|
||||
final a = 0.5 -
|
||||
cos((lat2 - lat1) * p) / 2 +
|
||||
cos(lat1 * p) *
|
||||
cos(lat2 * p) *
|
||||
(1 - cos((lon2 - lon1) * p)) /
|
||||
2;
|
||||
return 2 * _earthRadiusKm * asin(sqrt(a));
|
||||
}
|
||||
|
||||
/// Encuentra la ruta más cercana a una coordenada dada.
|
||||
/// Compara el centroide de cada ruta (promedio de sus posiciones).
|
||||
/// Cero Google Maps, cero costo, funciona offline.
|
||||
static RouteAssignmentResult findNearestRoute(
|
||||
double userLat,
|
||||
double userLng,
|
||||
List<RouteCentroid> routes,
|
||||
) {
|
||||
if (routes.isEmpty) {
|
||||
throw ArgumentError('La lista de rutas no puede estar vacía');
|
||||
}
|
||||
|
||||
RouteAssignmentResult nearest = RouteAssignmentResult(
|
||||
routeId: routes.first.routeId,
|
||||
routeName: routes.first.routeName,
|
||||
distanceKm: distanceKm(
|
||||
userLat,
|
||||
userLng,
|
||||
routes.first.centroidLat,
|
||||
routes.first.centroidLng,
|
||||
),
|
||||
);
|
||||
|
||||
for (final route in routes.skip(1)) {
|
||||
final d = distanceKm(
|
||||
userLat,
|
||||
userLng,
|
||||
route.centroidLat,
|
||||
route.centroidLng,
|
||||
);
|
||||
if (d < nearest.distanceKm) {
|
||||
nearest = RouteAssignmentResult(
|
||||
routeId: route.routeId,
|
||||
routeName: route.routeName,
|
||||
distanceKm: d,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/// Calcula el ETA estimado en minutos entre dos posiciones.
|
||||
static int etaMinutes(DateTime from, DateTime to) =>
|
||||
to.difference(from).inMinutes.abs();
|
||||
}
|
||||
|
||||
/// Centroide de una ruta (promedio lat/lng de todas sus posiciones)
|
||||
class RouteCentroid {
|
||||
final String routeId;
|
||||
final String routeName;
|
||||
final double centroidLat;
|
||||
final double centroidLng;
|
||||
|
||||
const RouteCentroid({
|
||||
required this.routeId,
|
||||
required this.routeName,
|
||||
required this.centroidLat,
|
||||
required this.centroidLng,
|
||||
});
|
||||
}
|
||||
|
||||
/// Resultado de la asignación espacial
|
||||
class RouteAssignmentResult {
|
||||
final String routeId;
|
||||
final String routeName;
|
||||
final double distanceKm;
|
||||
|
||||
const RouteAssignmentResult({
|
||||
required this.routeId,
|
||||
required this.routeName,
|
||||
required this.distanceKm,
|
||||
});
|
||||
|
||||
String get distanceText {
|
||||
if (distanceKm < 1.0) {
|
||||
return '${(distanceKm * 1000).toStringAsFixed(0)} m';
|
||||
}
|
||||
return '${distanceKm.toStringAsFixed(2)} km';
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
// lib/features/routes/domain/entities/route_entities.dart
|
||||
// Capa de dominio — cero dependencias externas.
|
||||
|
||||
class RoutePosition {
|
||||
final int positionId;
|
||||
final double lat;
|
||||
final double lng;
|
||||
final double speed;
|
||||
final DateTime timestamp;
|
||||
|
||||
const RoutePosition({
|
||||
required this.positionId,
|
||||
required this.lat,
|
||||
required this.lng,
|
||||
required this.speed,
|
||||
required this.timestamp,
|
||||
});
|
||||
|
||||
factory RoutePosition.fromJson(Map<String, dynamic> json) => RoutePosition(
|
||||
positionId: json['positionId'] as int,
|
||||
lat: (json['lat'] as num).toDouble(),
|
||||
lng: (json['lng'] as num).toDouble(),
|
||||
speed: (json['speed'] as num).toDouble(),
|
||||
timestamp: DateTime.parse(json['timestamp'] as String),
|
||||
);
|
||||
}
|
||||
|
||||
class TruckRoute {
|
||||
final String routeId;
|
||||
final String name;
|
||||
final int truckId;
|
||||
final String status;
|
||||
final List<RoutePosition> positions;
|
||||
|
||||
const TruckRoute({
|
||||
required this.routeId,
|
||||
required this.name,
|
||||
required this.truckId,
|
||||
required this.status,
|
||||
required this.positions,
|
||||
});
|
||||
|
||||
factory TruckRoute.fromJson(Map<String, dynamic> json) => TruckRoute(
|
||||
routeId: json['routeId'] as String,
|
||||
name: json['name'] as String,
|
||||
truckId: json['truckId'] as int,
|
||||
status: json['status'] as String,
|
||||
positions: (json['positions'] as List)
|
||||
.map((p) => RoutePosition.fromJson(p))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
/// Posición actual del camión (última del array, excluyendo el regreso)
|
||||
RoutePosition get currentPosition => positions[positions.length ~/ 2];
|
||||
|
||||
/// ETA estimado en minutos desde la posición actual hasta el final
|
||||
int etaFromPosition(int positionIndex) {
|
||||
if (positionIndex >= positions.length - 1) return 0;
|
||||
final current = positions[positionIndex];
|
||||
final last = positions[positions.length - 2]; // penúltima = fin de ruta
|
||||
return last.timestamp.difference(current.timestamp).inMinutes.abs();
|
||||
}
|
||||
}
|
||||
|
||||
/// Resultado de asignación de ruta por Haversine
|
||||
class RouteAssignment {
|
||||
final TruckRoute route;
|
||||
final double distanceKm;
|
||||
|
||||
const RouteAssignment({required this.route, required this.distanceKm});
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// lib/features/routes/presentation/providers/routes_provider.dart
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../data/repositories/routes_repository.dart';
|
||||
import '../../domain/entities/route_entities.dart';
|
||||
import '../../domain/entities/haversine.dart';
|
||||
|
||||
// ── Repositorio singleton ─────────────────────────────────────────────
|
||||
final routesRepositoryProvider = Provider<RoutesRepository>(
|
||||
(ref) => RoutesRepository(),
|
||||
);
|
||||
|
||||
// ── Todas las rutas ───────────────────────────────────────────────────
|
||||
final allRoutesProvider = FutureProvider<List<TruckRoute>>((ref) {
|
||||
return ref.watch(routesRepositoryProvider).obtenerRutas();
|
||||
});
|
||||
|
||||
// ── Ruta por ID ───────────────────────────────────────────────────────
|
||||
final routeByIdProvider =
|
||||
FutureProvider.family<TruckRoute?, String>((ref, routeId) {
|
||||
return ref.watch(routesRepositoryProvider).obtenerRutaPorId(routeId);
|
||||
});
|
||||
|
||||
// ── Asignación de ruta por coordenadas (Haversine) ────────────────────
|
||||
final routeAssignmentProvider =
|
||||
FutureProvider.family<RouteAssignmentResult, ({double lat, double lng})>(
|
||||
(ref, coords) {
|
||||
return ref
|
||||
.watch(routesRepositoryProvider)
|
||||
.asignarRuta(coords.lat, coords.lng);
|
||||
},
|
||||
);
|
||||
|
||||
// ── ETA para un domicilio ─────────────────────────────────────────────
|
||||
final etaProvider = FutureProvider.family<
|
||||
ETAResult,
|
||||
({String routeId, double lat, double lng})>(
|
||||
(ref, params) {
|
||||
return ref
|
||||
.watch(routesRepositoryProvider)
|
||||
.calcularETA(params.routeId, params.lat, params.lng);
|
||||
},
|
||||
);
|
||||
@@ -1,224 +0,0 @@
|
||||
// lib/features/routes/presentation/widgets/eta_card.dart
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../providers/routes_provider.dart';
|
||||
import '../../data/repositories/routes_repository.dart';
|
||||
|
||||
class ETACard extends ConsumerWidget {
|
||||
final String routeId;
|
||||
final double userLat;
|
||||
final double userLng;
|
||||
|
||||
const ETACard({
|
||||
super.key,
|
||||
required this.routeId,
|
||||
required this.userLat,
|
||||
required this.userLng,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final etaAsync = ref.watch(
|
||||
etaProvider((routeId: routeId, lat: userLat, lng: userLng)),
|
||||
);
|
||||
|
||||
return etaAsync.when(
|
||||
loading: () => const _ETACardSkeleton(),
|
||||
error: (e, _) => _ETACardError(error: e.toString()),
|
||||
data: (eta) => _ETACardContent(eta: eta),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ETACardContent extends StatelessWidget {
|
||||
final ETAResult eta;
|
||||
|
||||
const _ETACardContent({required this.eta});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _colorPorETA(eta.etaMinutos);
|
||||
|
||||
return Card(
|
||||
elevation: 4,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Header con ruta
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.local_shipping, color: color, size: 28),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
eta.routeName,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
_StatusChip(etaMinutos: eta.etaMinutos),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Ventana horaria — el "túnel" de privacidad
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: color.withOpacity(0.3)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
eta.ventana,
|
||||
style: TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: color,
|
||||
letterSpacing: 1,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Ventana de llegada estimada',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Mensaje accionable
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
size: 18,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
eta.mensaje,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.grey[700],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Badge de privacidad
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.lock_outline, size: 14, color: Colors.grey[500]),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'No compartimos tu ubicación exacta',
|
||||
style: TextStyle(fontSize: 11, color: Colors.grey[500]),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _colorPorETA(int minutos) {
|
||||
if (minutos <= 5) return Colors.red;
|
||||
if (minutos <= 15) return Colors.orange;
|
||||
return const Color(0xFF1B5E20);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatusChip extends StatelessWidget {
|
||||
final int etaMinutos;
|
||||
|
||||
const _StatusChip({required this.etaMinutos});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final (label, color) = switch (etaMinutos) {
|
||||
<= 0 => ('Llegando', Colors.red),
|
||||
<= 10 => ('¡Pronto!', Colors.orange),
|
||||
_ => ('En camino', const Color(0xFF2E7D32)),
|
||||
};
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: color.withOpacity(0.4)),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: color,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ETACardSkeleton extends StatelessWidget {
|
||||
const _ETACardSkeleton();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Card(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(20),
|
||||
child: Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ETACardError extends StatelessWidget {
|
||||
final String error;
|
||||
|
||||
const _ETACardError({required this.error});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.error_outline, color: Colors.red),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'No se pudo calcular el ETA: $error',
|
||||
style: const TextStyle(color: Colors.red, fontSize: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
// lib/features/routes/presentation/widgets/route_assignment_widget.dart
|
||||
// Este widget demuestra el motor espacial Haversine a los jueces.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../providers/routes_provider.dart';
|
||||
import '../../domain/entities/haversine.dart';
|
||||
|
||||
class RouteAssignmentWidget extends ConsumerWidget {
|
||||
final double userLat;
|
||||
final double userLng;
|
||||
|
||||
const RouteAssignmentWidget({
|
||||
super.key,
|
||||
required this.userLat,
|
||||
required this.userLng,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final assignmentAsync = ref.watch(
|
||||
routeAssignmentProvider((lat: userLat, lng: userLng)),
|
||||
);
|
||||
|
||||
return assignmentAsync.when(
|
||||
loading: () => const _AssignmentSkeleton(),
|
||||
error: (e, _) => Text('Error: $e'),
|
||||
data: (result) => _AssignmentResult(
|
||||
result: result,
|
||||
userLat: userLat,
|
||||
userLng: userLng,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AssignmentResult extends StatelessWidget {
|
||||
final RouteAssignmentResult result;
|
||||
final double userLat;
|
||||
final double userLng;
|
||||
|
||||
const _AssignmentResult({
|
||||
required this.result,
|
||||
required this.userLat,
|
||||
required this.userLng,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF1B5E20).withOpacity(0.05),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: const Color(0xFF1B5E20).withOpacity(0.2),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Título con ícono de motor espacial
|
||||
Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.calculate,
|
||||
color: Color(0xFF1B5E20),
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const Text(
|
||||
'Asignación automática',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 14,
|
||||
color: Color(0xFF1B5E20),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Container(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: const Text(
|
||||
'Haversine',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
color: Colors.blue,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Ruta asignada
|
||||
Text(
|
||||
result.routeId,
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Color(0xFF1B5E20),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
result.routeName,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.grey[700],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Distancia calculada
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.straighten, size: 16, color: Colors.grey),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'Distancia al centroide: ${result.distanceText}',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
|
||||
// Coordenadas del usuario (para debug/demo)
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.location_on, size: 16, color: Colors.grey),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'Tu ubicación: ${userLat.toStringAsFixed(4)}, ${userLng.toStringAsFixed(4)}',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// Nota de privacidad
|
||||
Container(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green.withOpacity(0.08),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.shield_outlined,
|
||||
size: 14,
|
||||
color: Color(0xFF2E7D32),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Motor espacial propio — sin llamadas externas',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: Colors.green[800],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AssignmentSkeleton extends StatelessWidget {
|
||||
const _AssignmentSkeleton();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
height: 120,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[100],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
// lib/features/routes/presentation/widgets/routes_list.dart
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../providers/routes_provider.dart';
|
||||
import '../../domain/entities/route_entities.dart';
|
||||
|
||||
class RoutesList extends ConsumerWidget {
|
||||
const RoutesList({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final rutasAsync = ref.watch(allRoutesProvider);
|
||||
|
||||
return rutasAsync.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (e, _) => Center(child: Text('Error: $e')),
|
||||
data: (rutas) => ListView.separated(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: rutas.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, i) => _RouteTile(ruta: rutas[i]),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RouteTile extends StatelessWidget {
|
||||
final TruckRoute ruta;
|
||||
|
||||
const _RouteTile({required this.ruta});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: const Color(0xFF1B5E20).withOpacity(0.1),
|
||||
child: Text(
|
||||
ruta.routeId.replaceAll('RUTA-', ''),
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF1B5E20),
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
ruta.name,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${ruta.positions.length - 1} paradas · Camión ${ruta.truckId}',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
|
||||
),
|
||||
trailing: _StatusBadge(status: ruta.status),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatusBadge extends StatelessWidget {
|
||||
final String status;
|
||||
|
||||
const _StatusBadge({required this.status});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final (color, icon) = switch (status) {
|
||||
'EN_RUTA' => (Colors.green, Icons.check_circle),
|
||||
'AVERIADA' => (Colors.red, Icons.error),
|
||||
'RETRASADA' => (Colors.orange, Icons.schedule),
|
||||
_ => (Colors.grey, Icons.help_outline),
|
||||
};
|
||||
|
||||
return Icon(icon, color: color, size: 20);
|
||||
}
|
||||
}
|
||||
190
lib/main.dart
190
lib/main.dart
@@ -1,190 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'core/config/supabase_config.dart';
|
||||
import 'core/theme/app_theme.dart';
|
||||
import 'core/ws_provider.dart';
|
||||
import 'features/recycling_guide/presentation/screens/recycling_guide_screen.dart';
|
||||
import 'features/routes/presentation/screens/routes_home_screen.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
await Supabase.initialize(
|
||||
url: SUPABASE_URL,
|
||||
anonKey: SUPABASE_ANON_KEY,
|
||||
);
|
||||
|
||||
runApp(const ProviderScope(child: MyApp()));
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Basura App - Notificación de Residuos',
|
||||
theme: AppTheme.lightTheme,
|
||||
home: const LoginScreen(),
|
||||
routes: {
|
||||
'/guia': (context) => const RecyclingGuideScreen(),
|
||||
'/rutas': (context) => const RoutesHomeScreen(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class LoginScreen extends ConsumerStatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends ConsumerState<LoginScreen> {
|
||||
final emailCtrl = TextEditingController();
|
||||
final passCtrl = TextEditingController();
|
||||
bool loading = false;
|
||||
String? error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
emailCtrl.dispose();
|
||||
passCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> login() async {
|
||||
setState(() {
|
||||
loading = true;
|
||||
error = null;
|
||||
});
|
||||
|
||||
try {
|
||||
// TODO: Llamar a endpoint /auth/login del backend en lugar de Supabase directo
|
||||
// Por ahora: simulación básica
|
||||
if (emailCtrl.text.isNotEmpty && passCtrl.text.isNotEmpty) {
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).pushReplacement(
|
||||
MaterialPageRoute(builder: (_) => const HomePage()),
|
||||
);
|
||||
} else {
|
||||
setState(() => error = 'Email y password requeridos');
|
||||
}
|
||||
} catch (e) {
|
||||
setState(() => error = 'Error: $e');
|
||||
} finally {
|
||||
setState(() => loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Login')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
TextField(
|
||||
controller: emailCtrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: passCtrl,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Password',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (error != null)
|
||||
Text(error!, style: const TextStyle(color: Colors.red)),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: loading ? null : login,
|
||||
child: loading
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(),
|
||||
)
|
||||
: const Text('Ingresar'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class HomePage extends ConsumerWidget {
|
||||
const HomePage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final wsState = ref.watch(wsProvider);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Basura App'),
|
||||
centerTitle: true,
|
||||
actions: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Center(
|
||||
child: Tooltip(
|
||||
message: wsState.connected ? 'Conectado' : 'Desconectado',
|
||||
child: Container(
|
||||
width: 12,
|
||||
height: 12,
|
||||
decoration: BoxDecoration(
|
||||
color: wsState.connected ? Colors.green : Colors.red,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// Estado WebSocket
|
||||
if (wsState.lastMessage != null)
|
||||
Container(
|
||||
color: Colors.blue[100],
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text('📬 ${wsState.lastMessage}'),
|
||||
),
|
||||
// Botones principales
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pushNamed(context, '/guia'),
|
||||
child: const Text('📚 Guía de Reciclaje'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pushNamed(context, '/rutas'),
|
||||
child: const Text('🚚 Rutas & ETA'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
157
lib/src/main.dart
Normal file
157
lib/src/main.dart
Normal file
@@ -0,0 +1,157 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
import '../core/config/supabase_config.dart';
|
||||
import '../core/ws_provider.dart';
|
||||
import 'views/rutas.dart';
|
||||
import 'views/login.dart';
|
||||
import 'views/home_screen.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
await Supabase.initialize(
|
||||
url: SUPABASE_URL,
|
||||
anonKey: SUPABASE_ANON_KEY,
|
||||
);
|
||||
|
||||
runApp(const ProviderScope(child: MyApp()));
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: 'Hackaton App',
|
||||
theme: ThemeData(
|
||||
fontFamily: 'Roboto',
|
||||
scaffoldBackgroundColor: const Color(0xFF0F0D38),
|
||||
),
|
||||
home: const RegistroView(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class RegistroView extends StatelessWidget {
|
||||
const RegistroView({super.key});
|
||||
|
||||
static const Color colorAzul = Color(0xFF0F0D38);
|
||||
static const Color colorVerde = Color(0xFF2E4D31);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.white,
|
||||
appBar: AppBar(
|
||||
backgroundColor: colorAzul,
|
||||
title: const Text(
|
||||
'Registro',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 28,
|
||||
),
|
||||
),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(30.0),
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 20),
|
||||
_buildInput(Icons.person_outline, 'Nombre Completo'),
|
||||
_buildInput(Icons.email_outlined, 'Correo'),
|
||||
_buildInput(Icons.lock_outline, 'Contraseña'),
|
||||
const SizedBox(height: 50),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorAzul,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 30, vertical: 15),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(15)),
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const HomeScreen()),
|
||||
);
|
||||
},
|
||||
child: const Text(
|
||||
'Registrar',
|
||||
style: TextStyle(color: Colors.white, fontSize: 18),
|
||||
),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorAzul,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 30, vertical: 15),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(15)),
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const LoginView()),
|
||||
);
|
||||
},
|
||||
child: const Text(
|
||||
'¿Tienes cuenta?',
|
||||
style: TextStyle(color: Colors.white, fontSize: 18),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInput(IconData icon, String hint) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 15),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: Colors.black, width: 2),
|
||||
),
|
||||
child: Icon(icon, size: 40, color: Colors.black),
|
||||
),
|
||||
const SizedBox(width: 15),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
decoration: InputDecoration(
|
||||
hintText: hint,
|
||||
hintStyle: TextStyle(
|
||||
color: colorVerde.withOpacity(0.5),
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 22,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 20, vertical: 15),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(30),
|
||||
borderSide: const BorderSide(color: colorVerde, width: 4),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
54
lib/src/models/domicilio_model.dart
Normal file
54
lib/src/models/domicilio_model.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class Domicilio {
|
||||
final String id;
|
||||
final String nombre;
|
||||
final String colonia;
|
||||
final String calle;
|
||||
final String numero;
|
||||
final double latitud;
|
||||
final double longitud;
|
||||
|
||||
Domicilio({
|
||||
required this.id,
|
||||
required this.nombre,
|
||||
required this.colonia,
|
||||
required this.calle,
|
||||
required this.numero,
|
||||
required this.latitud,
|
||||
required this.longitud,
|
||||
});
|
||||
|
||||
String get direccionCompleta => '$colonia, $calle $numero';
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'nombre': nombre,
|
||||
'colonia': colonia,
|
||||
'calle': calle,
|
||||
'numero': numero,
|
||||
'latitud': latitud,
|
||||
'longitud': longitud,
|
||||
};
|
||||
|
||||
factory Domicilio.fromJson(Map<String, dynamic> json) {
|
||||
return Domicilio(
|
||||
id: json['id'],
|
||||
nombre: json['nombre'],
|
||||
colonia: json['colonia'],
|
||||
calle: json['calle'],
|
||||
numero: json['numero'],
|
||||
latitud: json['latitud'].toDouble(),
|
||||
longitud: json['longitud'].toDouble(),
|
||||
);
|
||||
}
|
||||
|
||||
static String encode(List<Domicilio> domicilios) {
|
||||
return json.encode(domicilios.map((d) => d.toJson()).toList());
|
||||
}
|
||||
|
||||
static List<Domicilio> decode(String domiciliosString) {
|
||||
final List<dynamic> data = json.decode(domiciliosString);
|
||||
return data.map((item) => Domicilio.fromJson(item)).toList();
|
||||
}
|
||||
}
|
||||
72
lib/src/services/geolocation_service.dart
Normal file
72
lib/src/services/geolocation_service.dart
Normal file
@@ -0,0 +1,72 @@
|
||||
// src/services/geolocation_service.dart
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
|
||||
class SimplePosition {
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
final DateTime timestamp;
|
||||
|
||||
SimplePosition({
|
||||
required this.latitude,
|
||||
required this.longitude,
|
||||
required this.timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
class GeolocationService {
|
||||
static Future<bool> isLocationServiceEnabled() async {
|
||||
return await Geolocator.isLocationServiceEnabled();
|
||||
}
|
||||
|
||||
static Future<LocationPermission> checkPermission() async {
|
||||
return await Geolocator.checkPermission();
|
||||
}
|
||||
|
||||
static Future<LocationPermission> requestPermission() async {
|
||||
return await Geolocator.requestPermission();
|
||||
}
|
||||
|
||||
static Future<bool> hasPermission() async {
|
||||
LocationPermission permission = await Geolocator.checkPermission();
|
||||
return permission == LocationPermission.always ||
|
||||
permission == LocationPermission.whileInUse;
|
||||
}
|
||||
|
||||
static Future<SimplePosition?> getCurrentLocation() async {
|
||||
try {
|
||||
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
|
||||
if (!serviceEnabled) return null;
|
||||
|
||||
LocationPermission permission = await Geolocator.checkPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
permission = await Geolocator.requestPermission();
|
||||
if (permission == LocationPermission.denied) return null;
|
||||
}
|
||||
|
||||
if (permission == LocationPermission.deniedForever) return null;
|
||||
|
||||
Position position = await Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.low,
|
||||
timeLimit: const Duration(seconds: 5),
|
||||
);
|
||||
|
||||
return SimplePosition(
|
||||
latitude: position.latitude,
|
||||
longitude: position.longitude,
|
||||
timestamp: position.timestamp,
|
||||
);
|
||||
} catch (e) {
|
||||
print('Error: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<SimplePosition?> getCurrentLocationWithRetry({int maxRetries = 2}) async {
|
||||
for (int i = 0; i < maxRetries; i++) {
|
||||
final position = await getCurrentLocation();
|
||||
if (position != null) return position;
|
||||
if (i < maxRetries - 1) await Future.delayed(const Duration(seconds: 1));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
239
lib/src/views/configuracion.dart
Normal file
239
lib/src/views/configuracion.dart
Normal file
@@ -0,0 +1,239 @@
|
||||
// configuracion.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'rutas.dart';
|
||||
|
||||
class ConfiguracionView extends StatefulWidget {
|
||||
const ConfiguracionView({super.key});
|
||||
|
||||
@override
|
||||
State<ConfiguracionView> createState() => _ConfiguracionViewState();
|
||||
}
|
||||
|
||||
class _ConfiguracionViewState extends State<ConfiguracionView> {
|
||||
String selectedOption = '7 días'; // Valor por defecto
|
||||
bool _isLoading = true;
|
||||
|
||||
// Opciones del combobox
|
||||
final List<String> opciones = [
|
||||
'Cada día',
|
||||
'Cada 3 días',
|
||||
'Cada semana',
|
||||
'Cada quincena',
|
||||
];
|
||||
|
||||
// Mapa para mostrar valores más amigables
|
||||
final Map<String, String> opcionesMap = {
|
||||
'Cada día': '1 día',
|
||||
'Cada 3 días': '3 días',
|
||||
'Cada semana': '7 días',
|
||||
'Cada quincena': '15 días',
|
||||
};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarPreferencia();
|
||||
}
|
||||
|
||||
// Cargar la preferencia guardada
|
||||
Future<void> _cargarPreferencia() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final String? savedOption = prefs.getString('notificacion_frecuencia');
|
||||
|
||||
setState(() {
|
||||
if (savedOption != null && opciones.contains(savedOption)) {
|
||||
selectedOption = savedOption;
|
||||
}
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
print('Error al cargar preferencia: $e');
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Guardar la preferencia
|
||||
Future<void> _guardarPreferencia(String value) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('notificacion_frecuencia', value);
|
||||
|
||||
// Mostrar mensaje de confirmación
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Notificaciones: $value'),
|
||||
backgroundColor: colorAzul,
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
print('Error al guardar preferencia: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Mostrar diálogo con opciones
|
||||
void _mostrarSelector() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
'Frecuencia de notificaciones',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: colorAzul,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
...opciones.map((opcion) {
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
selectedOption == opcion ? Icons.radio_button_checked : Icons.radio_button_unchecked,
|
||||
color: colorAzul,
|
||||
),
|
||||
title: Text(
|
||||
opcion,
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: selectedOption == opcion ? FontWeight.bold : FontWeight.normal,
|
||||
color: selectedOption == opcion ? colorAzul : Colors.black87,
|
||||
),
|
||||
),
|
||||
trailing: Text(
|
||||
opcionesMap[opcion]!,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
selectedOption = opcion;
|
||||
});
|
||||
_guardarPreferencia(opcion);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 10),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: Colors.white,
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
// AppBar personalizado
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
|
||||
decoration: const BoxDecoration(
|
||||
color: colorAzul,
|
||||
borderRadius: BorderRadius.only(
|
||||
bottomLeft: Radius.circular(20),
|
||||
bottomRight: Radius.circular(20),
|
||||
),
|
||||
),
|
||||
child: const Text(
|
||||
'Configuración',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
// Contenido
|
||||
Expanded(
|
||||
child: _isLoading
|
||||
? const Center(
|
||||
child: CircularProgressIndicator(
|
||||
color: colorAzul,
|
||||
),
|
||||
)
|
||||
: Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Column(
|
||||
children: [
|
||||
// Selector de notificaciones
|
||||
GestureDetector(
|
||||
onTap: _mostrarSelector,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(15),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.black, width: 4),
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.notifications_active_outlined, size: 60),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
selectedOption,
|
||||
style: const TextStyle(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
const Icon(Icons.keyboard_arrow_down, size: 50),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
// Información adicional
|
||||
Container(
|
||||
padding: const EdgeInsets.all(15),
|
||||
decoration: BoxDecoration(
|
||||
color: colorAzul.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(15),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.info_outline, color: colorAzul, size: 30),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Recibirás notificaciones cada ${opcionesMap[selectedOption]}',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: colorAzul,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
379
lib/src/views/domicilios.dart
Normal file
379
lib/src/views/domicilios.dart
Normal file
@@ -0,0 +1,379 @@
|
||||
// domicilios.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'rutas.dart';
|
||||
import '../models/domicilio_model.dart';
|
||||
import '../services/geolocation_service.dart';
|
||||
|
||||
class DomiciliosView extends StatefulWidget {
|
||||
const DomiciliosView({super.key});
|
||||
|
||||
@override
|
||||
State<DomiciliosView> createState() => _DomiciliosViewState();
|
||||
}
|
||||
|
||||
class _DomiciliosViewState extends State<DomiciliosView> {
|
||||
List<Domicilio> domicilios = [];
|
||||
bool _isLoading = true;
|
||||
bool _isLoadingLocation = false;
|
||||
|
||||
final TextEditingController nombreController = TextEditingController();
|
||||
final TextEditingController coloniaController = TextEditingController();
|
||||
final TextEditingController calleController = TextEditingController();
|
||||
final TextEditingController numeroController = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarDomicilios();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
nombreController.dispose();
|
||||
coloniaController.dispose();
|
||||
calleController.dispose();
|
||||
numeroController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _cargarDomicilios() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final String? domiciliosString = prefs.getString('domicilios');
|
||||
|
||||
setState(() {
|
||||
if (domiciliosString != null && domiciliosString.isNotEmpty) {
|
||||
domicilios = Domicilio.decode(domiciliosString);
|
||||
}
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _guardarDomicilios() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final String domiciliosString = Domicilio.encode(domicilios);
|
||||
await prefs.setString('domicilios', domiciliosString);
|
||||
} catch (e) {
|
||||
print('Error al guardar: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _showLocationPermissionDialog() async {
|
||||
if (await GeolocationService.hasPermission()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Permiso de ubicación'),
|
||||
content: const Text(
|
||||
'Necesitamos acceder a tu ubicación para asignar tu domicilio a la ruta correcta.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancelar'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('Aceptar', style: TextStyle(color: colorAzul)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (result == true) {
|
||||
LocationPermission newPermission = await GeolocationService.requestPermission();
|
||||
return newPermission == LocationPermission.always ||
|
||||
newPermission == LocationPermission.whileInUse;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Future<void> _obtenerUbicacionYAgregar() async {
|
||||
setState(() {
|
||||
_isLoadingLocation = true;
|
||||
});
|
||||
|
||||
final serviceEnabled = await GeolocationService.isLocationServiceEnabled();
|
||||
if (!serviceEnabled) {
|
||||
setState(() {
|
||||
_isLoadingLocation = false;
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Activa el GPS para agregar un domicilio'),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final hasPermission = await _showLocationPermissionDialog();
|
||||
if (!hasPermission) {
|
||||
setState(() {
|
||||
_isLoadingLocation = false;
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Necesitamos tu ubicación'),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final simplePosition = await GeolocationService.getCurrentLocation();
|
||||
|
||||
setState(() {
|
||||
_isLoadingLocation = false;
|
||||
});
|
||||
|
||||
if (simplePosition == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('No se pudo obtener tu ubicación.'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
_mostrarDialogoAgregarConUbicacion(simplePosition.latitude, simplePosition.longitude);
|
||||
}
|
||||
|
||||
void _mostrarDialogoAgregarConUbicacion(double lat, double lng) {
|
||||
nombreController.clear();
|
||||
coloniaController.clear();
|
||||
calleController.clear();
|
||||
numeroController.clear();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (BuildContext context) {
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('Añadir domicilio', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: colorAzul)),
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(color: Colors.green.withOpacity(0.1), borderRadius: BorderRadius.circular(12)),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.location_on, color: Colors.green[700], size: 24),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('📍 Ubicación obtenida', style: TextStyle(fontSize: 12, color: Colors.green[700])),
|
||||
Text('Lat: ${lat.toStringAsFixed(6)}'),
|
||||
Text('Lng: ${lng.toStringAsFixed(6)}'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 15),
|
||||
_buildCampoTexto(controller: nombreController, hint: 'Nombre del domicilio', icon: Icons.home_outlined),
|
||||
const SizedBox(height: 15),
|
||||
_buildCampoTexto(controller: coloniaController, hint: 'Colonia', icon: Icons.location_city_outlined),
|
||||
const SizedBox(height: 15),
|
||||
_buildCampoTexto(controller: calleController, hint: 'Calle', icon: Icons.streetview),
|
||||
const SizedBox(height: 15),
|
||||
_buildCampoTexto(controller: numeroController, hint: 'Número', icon: Icons.numbers, keyboardType: TextInputType.number),
|
||||
const SizedBox(height: 25),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
style: OutlinedButton.styleFrom(side: BorderSide(color: colorAzul, width: 2), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancelar', style: TextStyle(color: colorAzul)),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 15),
|
||||
Expanded(
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: colorAzul, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
|
||||
onPressed: () => _agregarDomicilio(latitud: lat, longitud: lng),
|
||||
child: const Text('Agregar', style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCampoTexto({
|
||||
required TextEditingController controller,
|
||||
required String hint,
|
||||
required IconData icon,
|
||||
TextInputType keyboardType = TextInputType.text,
|
||||
}) {
|
||||
return TextField(
|
||||
controller: controller,
|
||||
keyboardType: keyboardType,
|
||||
decoration: InputDecoration(
|
||||
hintText: hint,
|
||||
prefixIcon: Icon(icon, color: colorAzul),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(15)),
|
||||
enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: BorderSide(color: colorAzul.withOpacity(0.5))),
|
||||
focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: colorAzul, width: 2)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _agregarDomicilio({required double latitud, required double longitud}) async {
|
||||
if (nombreController.text.trim().isEmpty ||
|
||||
coloniaController.text.trim().isEmpty ||
|
||||
calleController.text.trim().isEmpty ||
|
||||
numeroController.text.trim().isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Llena todos los campos'), backgroundColor: Colors.red),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final nuevoDomicilio = Domicilio(
|
||||
id: DateTime.now().millisecondsSinceEpoch.toString(),
|
||||
nombre: nombreController.text.trim(),
|
||||
colonia: coloniaController.text.trim(),
|
||||
calle: calleController.text.trim(),
|
||||
numero: numeroController.text.trim(),
|
||||
latitud: latitud,
|
||||
longitud: longitud,
|
||||
);
|
||||
|
||||
setState(() {
|
||||
domicilios.add(nuevoDomicilio);
|
||||
});
|
||||
|
||||
await _guardarDomicilios();
|
||||
Navigator.pop(context);
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Domicilio agregado'), backgroundColor: colorAzul),
|
||||
);
|
||||
}
|
||||
|
||||
void _eliminarDomicilio(int index) async {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Eliminar domicilio'),
|
||||
content: Text('¿Eliminar "${domicilios[index].nombre}"?'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancelar')),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
setState(() => domicilios.removeAt(index));
|
||||
await _guardarDomicilios();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Eliminar', style: TextStyle(color: Colors.red)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
|
||||
decoration: const BoxDecoration(
|
||||
color: colorAzul,
|
||||
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
|
||||
),
|
||||
child: const Text('Domicilios', style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold), textAlign: TextAlign.center),
|
||||
),
|
||||
Expanded(
|
||||
child: _isLoading
|
||||
? const Center(child: CircularProgressIndicator(color: colorAzul))
|
||||
: domicilios.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.home_outlined, size: 100, color: Colors.grey.withOpacity(0.5)),
|
||||
const SizedBox(height: 20),
|
||||
Text('No hay domicilios', style: TextStyle(fontSize: 18, color: Colors.grey.withOpacity(0.7))),
|
||||
const SizedBox(height: 10),
|
||||
Text('Toca el botón + para agregar', style: TextStyle(fontSize: 14, color: Colors.grey.withOpacity(0.5))),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.all(20),
|
||||
itemCount: domicilios.length,
|
||||
itemBuilder: (context, index) {
|
||||
final d = domicilios[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 20),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(15),
|
||||
decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(25)),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.home_outlined, size: 60),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(d.nombre, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
|
||||
Text(d.direccionCompleta, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
|
||||
Text('📍 ${d.latitud.toStringAsFixed(4)}, ${d.longitud.toStringAsFixed(4)}', style: TextStyle(fontSize: 12, color: Colors.grey[600])),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(onPressed: () => _eliminarDomicilio(index), icon: const Icon(Icons.delete_outline, size: 40), color: Colors.red),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: _isLoadingLocation
|
||||
? Container(width: double.infinity, height: 100, decoration: BoxDecoration(color: colorAzul, borderRadius: BorderRadius.circular(20)), child: const Center(child: CircularProgressIndicator(color: Colors.white)))
|
||||
: GestureDetector(
|
||||
onTap: _obtenerUbicacionYAgregar,
|
||||
child: Container(width: double.infinity, height: 100, decoration: BoxDecoration(color: colorAzul, borderRadius: BorderRadius.circular(20)), child: const Icon(Icons.add, color: Colors.white, size: 80)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
42
lib/src/views/home_screen.dart
Normal file
42
lib/src/views/home_screen.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
//home_screen.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'domicilios.dart';
|
||||
import 'horarios.dart';
|
||||
import 'configuracion.dart';
|
||||
import 'rutas.dart';
|
||||
import 'nav_bar.dart';
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
const HomeScreen({super.key});
|
||||
|
||||
@override
|
||||
State<HomeScreen> createState() => _HomeScreenState();
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> {
|
||||
int _currentIndex = 0; // 0: Domicilios, 1: Rutas, 2: Configuración
|
||||
|
||||
final List<Widget> _paginas = const [
|
||||
DomiciliosView(),
|
||||
HorariosView(),
|
||||
ConfiguracionView(),
|
||||
];
|
||||
|
||||
void _onNavBarTap(int index) {
|
||||
setState(() {
|
||||
_currentIndex = index;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.white,
|
||||
body: _paginas[_currentIndex],
|
||||
bottomNavigationBar: CustomNavBar(
|
||||
currentIndex: _currentIndex,
|
||||
onTap: _onNavBarTap,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
224
lib/src/views/horarios.dart
Normal file
224
lib/src/views/horarios.dart
Normal file
@@ -0,0 +1,224 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'rutas.dart';
|
||||
import '../models/domicilio_model.dart';
|
||||
import 'mapa_expandible.dart';
|
||||
|
||||
class HorariosView extends StatefulWidget {
|
||||
const HorariosView({super.key});
|
||||
|
||||
@override
|
||||
State<HorariosView> createState() => _HorariosViewState();
|
||||
}
|
||||
|
||||
class _HorariosViewState extends State<HorariosView> {
|
||||
List<Domicilio> domicilios = [];
|
||||
bool _isLoading = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarDomicilios();
|
||||
}
|
||||
|
||||
Future<void> _cargarDomicilios() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final String? domiciliosString = prefs.getString('domicilios');
|
||||
|
||||
setState(() {
|
||||
if (domiciliosString != null && domiciliosString.isNotEmpty) {
|
||||
domicilios = Domicilio.decode(domiciliosString);
|
||||
}
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: Colors.white,
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
// AppBar personalizado
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
|
||||
decoration: const BoxDecoration(
|
||||
color: colorAzul,
|
||||
borderRadius: BorderRadius.only(
|
||||
bottomLeft: Radius.circular(20),
|
||||
bottomRight: Radius.circular(20),
|
||||
),
|
||||
),
|
||||
child: const Text(
|
||||
'Mis Rutas',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
// Lista de domicilios
|
||||
Expanded(
|
||||
child: _isLoading
|
||||
? const Center(child: CircularProgressIndicator(color: colorAzul))
|
||||
: domicilios.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.location_on_outlined,
|
||||
size: 100,
|
||||
color: Colors.grey.withOpacity(0.5),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
'No hay domicilios agregados',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
color: Colors.grey.withOpacity(0.7),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Agrega domicilios desde la pestaña Domicilios',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey.withOpacity(0.5),
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.all(20),
|
||||
itemCount: domicilios.length,
|
||||
itemBuilder: (context, index) {
|
||||
final domicilio = domicilios[index];
|
||||
return _buildDomicilioCard(domicilio, index);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDomicilioCard(Domicilio domicilio, int index) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 20),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.black, width: 4),
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
// Contenido principal del domicilio
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(15),
|
||||
child: Column(
|
||||
children: [
|
||||
// Info principal
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.home_outlined, size: 60),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
domicilio.nombre,
|
||||
style: const TextStyle(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
domicilio.direccionCompleta,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'📍 ${domicilio.latitud.toStringAsFixed(4)}, ${domicilio.longitud.toStringAsFixed(4)}',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
// Fila de horario y botón de mapa
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// Horario (placeholder para API del backend)
|
||||
Expanded(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorAzul.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.access_time, color: colorAzul, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Horario: ${_obtenerHorarioEstimado(index)}',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: colorAzul,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Botón/flecha para mapa desplegable
|
||||
MapaExpandible(
|
||||
latitud: domicilio.latitud,
|
||||
longitud: domicilio.longitud,
|
||||
nombreDomicilio: domicilio.nombre,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Horario estimado (placeholder para cuando conectes con el backend)
|
||||
String _obtenerHorarioEstimado(int index) {
|
||||
// Esto es solo un placeholder - aquí irá la llamada a tu API
|
||||
final horarios = ['8:00 AM - 9:00 AM', '9:30 AM - 10:30 AM', '11:00 AM - 12:00 PM', '1:00 PM - 2:00 PM', '3:00 PM - 4:00 PM', '5:00 PM - 6:00 PM'];
|
||||
return horarios[index % horarios.length];
|
||||
}
|
||||
}
|
||||
111
lib/src/views/login.dart
Normal file
111
lib/src/views/login.dart
Normal file
@@ -0,0 +1,111 @@
|
||||
// login.dart - cambiar MainScreen por HomeScreen
|
||||
import 'package:flutter/material.dart';
|
||||
import 'rutas.dart';
|
||||
import 'home_screen.dart'; // ← Importar HomeScreen
|
||||
|
||||
class LoginView extends StatelessWidget {
|
||||
const LoginView({super.key});
|
||||
|
||||
final Color colorAzul = const Color(0xFF0F0D38);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.white,
|
||||
appBar: AppBar(
|
||||
backgroundColor: colorAzul,
|
||||
title: const Text('Iniciar Sesión',
|
||||
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 28)),
|
||||
centerTitle: true,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back, color: Colors.white, size: 30),
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(30.0),
|
||||
child: Column(
|
||||
children: [
|
||||
_buildInput(Icons.email_outlined, 'Correo electrónico', obscureText: false),
|
||||
const SizedBox(height: 20),
|
||||
_buildInput(Icons.lock_outline, 'Contraseña', obscureText: true),
|
||||
const SizedBox(height: 50),
|
||||
Column(
|
||||
children: [
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorAzul,
|
||||
minimumSize: const Size(double.infinity, 55),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
|
||||
),
|
||||
onPressed: () {
|
||||
// ✅ Navegar a HomeScreen
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => const HomeScreen()),
|
||||
);
|
||||
},
|
||||
child: const Text(
|
||||
'Iniciar Sesión',
|
||||
style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
OutlinedButton(
|
||||
style: OutlinedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 55),
|
||||
side: BorderSide(color: colorAzul, width: 2),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Text(
|
||||
'Crear Cuenta',
|
||||
style: TextStyle(color: colorAzul, fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInput(IconData icon, String hint, {bool obscureText = false}) {
|
||||
return Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: Colors.black, width: 2),
|
||||
),
|
||||
child: Icon(icon, size: 40, color: Colors.black),
|
||||
),
|
||||
const SizedBox(width: 15),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
obscureText: obscureText,
|
||||
decoration: InputDecoration(
|
||||
hintText: hint,
|
||||
hintStyle: TextStyle(color: colorAzul.withOpacity(0.5), fontWeight: FontWeight.bold, fontSize: 22),
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(30),
|
||||
borderSide: BorderSide(color: colorAzul, width: 4),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(30),
|
||||
borderSide: BorderSide(color: colorAzul, width: 4),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
70
lib/src/views/main_screen.dart
Normal file
70
lib/src/views/main_screen.dart
Normal file
@@ -0,0 +1,70 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'rutas.dart';
|
||||
import 'domicilios.dart';
|
||||
import 'horarios.dart';
|
||||
import 'configuracion.dart';
|
||||
import 'nav_bar.dart';
|
||||
|
||||
class MainScreen extends StatefulWidget {
|
||||
const MainScreen({super.key});
|
||||
|
||||
@override
|
||||
State<MainScreen> createState() => _MainScreenState();
|
||||
}
|
||||
|
||||
class _MainScreenState extends State<MainScreen> {
|
||||
late PageController _pageController;
|
||||
int _currentIndex = 1; // Comenzar en Horarios (Rutas)
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_pageController = PageController(initialPage: _currentIndex);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pageController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onPageChanged(int index) {
|
||||
setState(() {
|
||||
_currentIndex = index;
|
||||
});
|
||||
}
|
||||
|
||||
void _onNavBarTap(int index) {
|
||||
if (_currentIndex != index) {
|
||||
setState(() {
|
||||
_currentIndex = index;
|
||||
});
|
||||
_pageController.animateToPage(
|
||||
index,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: colorAzul, // Mismo color de fondo para evitar flash blanco
|
||||
body: PageView(
|
||||
controller: _pageController,
|
||||
onPageChanged: _onPageChanged,
|
||||
physics: const BouncingScrollPhysics(), // Efecto de rebote al deslizar
|
||||
children: const [
|
||||
DomiciliosView(),
|
||||
HorariosView(),
|
||||
ConfiguracionView(),
|
||||
],
|
||||
),
|
||||
bottomNavigationBar: CustomNavBar(
|
||||
currentIndex: _currentIndex,
|
||||
onTap: _onNavBarTap,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
138
lib/src/views/mapa_expandible.dart
Normal file
138
lib/src/views/mapa_expandible.dart
Normal file
@@ -0,0 +1,138 @@
|
||||
// src/views/mapa_expandible.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'rutas.dart';
|
||||
|
||||
class MapaExpandible extends StatefulWidget {
|
||||
final double latitud;
|
||||
final double longitud;
|
||||
final String nombreDomicilio;
|
||||
|
||||
const MapaExpandible({
|
||||
super.key,
|
||||
required this.latitud,
|
||||
required this.longitud,
|
||||
required this.nombreDomicilio,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MapaExpandible> createState() => _MapaExpandibleState();
|
||||
}
|
||||
|
||||
class _MapaExpandibleState extends State<MapaExpandible> {
|
||||
bool _isExpanded = false;
|
||||
|
||||
bool get _isValidLatLng {
|
||||
final lat = widget.latitud;
|
||||
final lng = widget.longitud;
|
||||
return lat.isFinite && lng.isFinite && lat != 0 && lng != 0;
|
||||
}
|
||||
|
||||
Future<void> _abrirGoogleMaps() async {
|
||||
final url = 'https://www.google.com/maps?q=${widget.latitud},${widget.longitud}&z=15';
|
||||
try {
|
||||
if (await canLaunch(url)) {
|
||||
await launch(url);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('No se pudo abrir el mapa'), backgroundColor: Colors.red),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!_isValidLatLng) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[200],
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: const Text('Ubicación no disponible', style: TextStyle(fontSize: 12)),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_isExpanded = !_isExpanded;
|
||||
});
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[200],
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
_isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
|
||||
color: colorAzul,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
_isExpanded ? 'Ocultar mapa' : 'Ver mapa',
|
||||
style: TextStyle(color: colorAzul, fontSize: 12, fontWeight: FontWeight.w500),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_isExpanded)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: GestureDetector(
|
||||
onTap: _abrirGoogleMaps,
|
||||
child: Container(
|
||||
width: 200, // Ancho fijo en lugar de infinity
|
||||
height: 160,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(15),
|
||||
border: Border.all(color: colorAzul.withOpacity(0.3), width: 1),
|
||||
color: Colors.grey[100],
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.map, size: 40, color: colorAzul),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Ver en Google Maps',
|
||||
style: TextStyle(color: colorAzul, fontWeight: FontWeight.bold, fontSize: 14),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${widget.latitud.toStringAsFixed(4)}, ${widget.longitud.toStringAsFixed(4)}',
|
||||
style: TextStyle(fontSize: 11, color: Colors.grey[600]),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: colorAzul,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Text(
|
||||
'Tocar para abrir',
|
||||
style: TextStyle(color: Colors.white, fontSize: 11),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
86
lib/src/views/nav_bar.dart
Normal file
86
lib/src/views/nav_bar.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'rutas.dart';
|
||||
|
||||
class CustomNavBar extends StatelessWidget {
|
||||
final int currentIndex;
|
||||
final Function(int) onTap;
|
||||
|
||||
const CustomNavBar({
|
||||
super.key,
|
||||
required this.currentIndex,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
height: 90,
|
||||
color: colorAzul,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
_buildNavButton(
|
||||
index: 0,
|
||||
currentIndex: currentIndex,
|
||||
iconNormal: Icons.home_outlined,
|
||||
iconActive: Icons.home,
|
||||
label: 'Domicilios',
|
||||
onTap: onTap,
|
||||
),
|
||||
_buildNavButton(
|
||||
index: 1,
|
||||
currentIndex: currentIndex,
|
||||
iconNormal: Icons.alt_route_rounded,
|
||||
iconActive: Icons.alt_route_rounded,
|
||||
label: 'Rutas',
|
||||
onTap: onTap,
|
||||
),
|
||||
_buildNavButton(
|
||||
index: 2,
|
||||
currentIndex: currentIndex,
|
||||
iconNormal: Icons.settings_outlined,
|
||||
iconActive: Icons.settings,
|
||||
label: 'Configuración',
|
||||
onTap: onTap,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNavButton({
|
||||
required int index,
|
||||
required int currentIndex,
|
||||
required IconData iconNormal,
|
||||
required IconData iconActive,
|
||||
required String label,
|
||||
required Function(int) onTap,
|
||||
}) {
|
||||
final bool isActive = currentIndex == index;
|
||||
|
||||
return Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: () => onTap(index),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
isActive ? iconActive : iconNormal,
|
||||
color: Colors.white,
|
||||
size: isActive ? 55 : 35,
|
||||
),
|
||||
const SizedBox(height: 5),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: isActive ? 14 : 12,
|
||||
fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
4
lib/src/views/rutas.dart
Normal file
4
lib/src/views/rutas.dart
Normal file
@@ -0,0 +1,4 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
const Color colorAzul = Color(0xFF0F0D38);
|
||||
const Color colorAzulClaro = Color(0xFF2A2A5E);
|
||||
Reference in New Issue
Block a user