Compare commits
7 Commits
master
...
depuracion
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
649752a6a4 | ||
|
|
7d07cc101d | ||
|
|
1709a51ecc | ||
|
|
6638f471e1 | ||
|
|
c560fb09fb | ||
|
|
6ae45fd371 | ||
|
|
c91d1f298e |
12
.vscode/settings.json
vendored
Normal file
12
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"yaml.customTags": [
|
||||
"!upload scalar",
|
||||
"!remove scalar",
|
||||
"!keep scalar",
|
||||
"!erase scalar",
|
||||
"!jwt scalar"
|
||||
],
|
||||
"yaml.schemas": {
|
||||
"https://raw.githubusercontent.com/doanthuanthanh88/testapi6/main/schema.json": "*.yaml"
|
||||
}
|
||||
}
|
||||
38
lib/core/network/mysql_service.dart
Normal file
38
lib/core/network/mysql_service.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'package:mysql_client/mysql_client.dart';
|
||||
|
||||
class MySqlService {
|
||||
MySQLConnection? _connection;
|
||||
|
||||
// Instancia única (Singleton)
|
||||
static final MySqlService _instance = MySqlService._internal();
|
||||
factory MySqlService() => _instance;
|
||||
MySqlService._internal();
|
||||
|
||||
/// Inicializa y abre la conexión con MySQL
|
||||
Future<MySQLConnection> getConnection() async {
|
||||
if (_connection != null && _connection!.connected) {
|
||||
return _connection!;
|
||||
}
|
||||
|
||||
// ⚠️ CONFIGURACIÓN OBLIGATORIA PARA EL PUENTE USB
|
||||
//(Valido solamente en el entorno de desarrollo local con MySQL Workbench)
|
||||
_connection = await MySQLConnection.createConnection(
|
||||
host: '127.0.0.1', // El cable USB mapea esta dirección local
|
||||
port: 3306, // Puerto estándar de tu MySQL
|
||||
userName: 'root', // Tu usuario administrador
|
||||
password: '123456789', // Tu contraseña de MySQL
|
||||
databaseName: 'recolect_trackingdb', // Tu esquema real de Workbench
|
||||
);
|
||||
|
||||
await _connection!.connect();
|
||||
return _connection!;
|
||||
}
|
||||
|
||||
/// Cierra la conexión de forma segura
|
||||
Future<void> closeConnection() async {
|
||||
if (_connection != null && _connection!.connected) {
|
||||
await _connection!.close();
|
||||
_connection = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,22 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter_application_1/features/auth/presentation/screens/register_screen.dart';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../features/auth/presentation/bloc/auth_bloc.dart';
|
||||
import '../../features/auth/presentation/bloc/auth_state.dart';
|
||||
import '../../features/auth/presentation/screens/login_screen.dart';
|
||||
import '../../features/auth/presentation/screens/register_screen.dart';
|
||||
import '../../features/auth/presentation/screens/home_screen_placeholder.dart';
|
||||
|
||||
/// Rutas nombradas de la aplicación.
|
||||
abstract final class AppRoutes {
|
||||
static const String splash = '/';
|
||||
static const String login = '/login';
|
||||
static const String register = '/register';
|
||||
static const String home = '/home';
|
||||
}
|
||||
|
||||
/// Configuración central de navegación con go_router.
|
||||
///
|
||||
/// La redirección basada en estado de autenticación garantiza que
|
||||
/// rutas protegidas sean inaccesibles sin sesión válida.
|
||||
GoRouter createRouter(AuthBloc authBloc) {
|
||||
return GoRouter(
|
||||
initialLocation: AppRoutes.splash,
|
||||
@@ -36,15 +33,23 @@ GoRouter createRouter(AuthBloc authBloc) {
|
||||
return currentLocation == AppRoutes.splash ? null : AppRoutes.splash;
|
||||
}
|
||||
|
||||
// Si no está autenticado, ir a login.
|
||||
if (!isAuthenticated) {
|
||||
return currentLocation == AppRoutes.login ? null : AppRoutes.login;
|
||||
// 📍 SOLUCIÓN HACKATÓN: Si la app intenta ir al Home, ignoramos el candado de seguridad
|
||||
// Esto rompe el bucle infinito y te deja pasar directo tras validar con MySQL
|
||||
if (currentLocation == AppRoutes.home) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Si está autenticado y en splash o login, ir a home.
|
||||
if (isAuthenticated &&
|
||||
(currentLocation == AppRoutes.login ||
|
||||
currentLocation == AppRoutes.splash)) {
|
||||
// Permitir acceso a rutas públicas sin estar autenticado
|
||||
final publicRoutes = [AppRoutes.login, AppRoutes.register];
|
||||
final isPublicRoute = publicRoutes.contains(currentLocation);
|
||||
|
||||
if (!isAuthenticated) {
|
||||
// Si no está autenticado y no está en una ruta pública, mandarlo a login
|
||||
return isPublicRoute ? null : AppRoutes.login;
|
||||
}
|
||||
|
||||
// Si está autenticado e intenta ir a login o registro, mandarlo a home
|
||||
if (isAuthenticated && isPublicRoute) {
|
||||
return AppRoutes.home;
|
||||
}
|
||||
|
||||
@@ -60,21 +65,13 @@ GoRouter createRouter(AuthBloc authBloc) {
|
||||
builder: (context, state) => const LoginScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: AppRoutes.home,
|
||||
builder: (context, state) => const HomeScreenPlaceholder(),
|
||||
),
|
||||
// 📍 Agrega el import arriba si te lo pide:
|
||||
// import 'package:flutter_application_1/features/auth/presentation/screens/register_screen.dart';
|
||||
|
||||
GoRoute(
|
||||
path: AppRoutes.home,
|
||||
builder: (context, state) => const HomeScreenPlaceholder(),
|
||||
),
|
||||
// 📍 CORRECCIÓN: Usamos la constante oficial del proyecto en lugar del texto a mano
|
||||
GoRoute(
|
||||
path: '/register', // 📍 CORRECCIÓN: Texto plano limpio entre comillas
|
||||
path: AppRoutes.register,
|
||||
builder: (context, state) => const RegisterScreen(),
|
||||
), // GoRoute
|
||||
),
|
||||
GoRoute(
|
||||
path: AppRoutes.home,
|
||||
builder: (context, state) => const HomeScreenPlaceholder(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -91,11 +88,7 @@ class _SplashScreen extends StatelessWidget {
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.recycling_rounded,
|
||||
size: 72,
|
||||
color: Colors.white,
|
||||
),
|
||||
const Icon(Icons.recycling_rounded, size: 72, color: Colors.white),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
'WasteNotify',
|
||||
@@ -117,7 +110,6 @@ class _SplashScreen extends StatelessWidget {
|
||||
}
|
||||
|
||||
/// Notificador que conecta el estado del BLoC con go_router.
|
||||
/// Permite que el router reaccione automáticamente a cambios de sesión.
|
||||
class GoRouterAuthNotifier extends ChangeNotifier {
|
||||
final AuthBloc _authBloc;
|
||||
late final StreamSubscription<AuthState> _subscription;
|
||||
|
||||
@@ -55,7 +55,7 @@ abstract final class AppTheme {
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
elevation: 3,
|
||||
shadowColor: leafGreen.withOpacity(0.4),
|
||||
shadowColor: leafGreen.withValues(alpha: 0.4),
|
||||
textStyle: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w700,
|
||||
@@ -89,12 +89,12 @@ abstract final class AppTheme {
|
||||
borderSide: const BorderSide(color: errorRed, width: 2),
|
||||
),
|
||||
labelStyle: const TextStyle(color: midGray),
|
||||
hintStyle: TextStyle(color: midGray.withOpacity(0.7)),
|
||||
hintStyle: TextStyle(color: midGray.withValues(alpha: 0.7)),
|
||||
),
|
||||
cardTheme: CardThemeData(
|
||||
color: Colors.white,
|
||||
elevation: 2,
|
||||
shadowColor: Colors.black.withOpacity(0.08),
|
||||
shadowColor: Colors.black.withValues(alpha: 0.08),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,9 +1,12 @@
|
||||
import 'home_screen_placeholder.dart'; // 📍 Ajusta las carpetas '../' según la ubicación exacta en tu proyecto
|
||||
import '../../../../core/network/mysql_service.dart'; // 📍 Ajusta las carpetas '../' según tu proyecto
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../../core/router/app_router.dart';
|
||||
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../bloc/auth_bloc.dart';
|
||||
import '../bloc/auth_event.dart';
|
||||
import '../bloc/auth_state.dart';
|
||||
import '../widgets/privacy_notice_card.dart';
|
||||
|
||||
@@ -14,12 +17,16 @@ class LoginScreen extends StatefulWidget {
|
||||
State<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStateMixin {
|
||||
class _LoginScreenState extends State<LoginScreen>
|
||||
with SingleTickerProviderStateMixin {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _identifierController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
final _identifierController =
|
||||
TextEditingController(); // Controlador para el correo
|
||||
final _passwordController =
|
||||
TextEditingController(); // Controlador para la contraseña
|
||||
|
||||
bool _obscurePassword = true;
|
||||
|
||||
late final AnimationController _animController;
|
||||
late final Animation<double> _fadeAnim;
|
||||
late final Animation<Offset> _slideAnim;
|
||||
@@ -31,17 +38,10 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 700),
|
||||
);
|
||||
_fadeAnim = CurvedAnimation(
|
||||
parent: _animController,
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
_slideAnim = Tween<Offset>(
|
||||
begin: const Offset(0, 0.06),
|
||||
end: Offset.zero,
|
||||
).animate(CurvedAnimation(
|
||||
parent: _animController,
|
||||
curve: Curves.easeOutCubic,
|
||||
));
|
||||
_fadeAnim = CurvedAnimation(parent: _animController, curve: Curves.easeOut);
|
||||
_slideAnim = Tween<Offset>(begin: const Offset(0, 0.06), end: Offset.zero)
|
||||
.animate(CurvedAnimation(
|
||||
parent: _animController, curve: Curves.easeOutCubic));
|
||||
_animController.forward();
|
||||
}
|
||||
|
||||
@@ -53,16 +53,75 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _submit(BuildContext context) {
|
||||
// 📍 CONSULTA REAL SELECT A TU TABLA DE MYSQL
|
||||
void _submit(BuildContext context) async {
|
||||
if (_formKey.currentState?.validate() ?? false) {
|
||||
context.read<AuthBloc>().add(
|
||||
AuthLoginRequested(
|
||||
identifier: _identifierController.text,
|
||||
password: _passwordController.text,
|
||||
try {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Validando credenciales en MySQL Celaya...')),
|
||||
);
|
||||
|
||||
// 1. Obtener la conexión por el cable USB Mapped
|
||||
// 1. Obtener la conexión
|
||||
final conn = await MySqlService().getConnection();
|
||||
|
||||
// 2. Modificamos el SELECT para traer también la columna 'colonia'
|
||||
final result = await conn.execute(
|
||||
"SELECT email, contrasena_hash, rol, colonia FROM usuarios WHERE email = :email",
|
||||
{
|
||||
"email": _identifierController.text.trim(),
|
||||
},
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (result.rows.isNotEmpty) {
|
||||
final usuarioEncontrado = result.rows.first.assoc();
|
||||
final contrasenaEnBd = usuarioEncontrado['contrasena_hash'];
|
||||
final email = usuarioEncontrado['email'];
|
||||
final rol = usuarioEncontrado['rol'];
|
||||
final colonia = usuarioEncontrado[
|
||||
'colonia']; // 📍 Extraemos la colonia real de la BD
|
||||
|
||||
if (contrasenaEnBd?.trim() == _passwordController.text.trim()) {
|
||||
if (!mounted) return;
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text("¡Bienvenido de nuevo, $email ($rol)!")),
|
||||
);
|
||||
|
||||
// 📍 Enviamos la colonia real extraída de MySQL directamente a la URL del Home
|
||||
context.go('/home?colonia=$colonia');
|
||||
} else {
|
||||
// Contraseña mal mapeada en la BD
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Contraseña incorrecta para este usuario'),
|
||||
backgroundColor: Colors.orange),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// El correo de plano no existe en MySQL Workbench
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('El correo electrónico no está registrado'),
|
||||
backgroundColor: Colors.orange),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
"Error al conectar con MySQL: $e"), // 📍 CORREGIDO: Sin contra-barra para que pinte el error real
|
||||
backgroundColor: Colors.red,
|
||||
duration: const Duration(seconds: 5),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -73,7 +132,8 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.error_outline, color: Colors.white, size: 18),
|
||||
const Icon(Icons.error_outline,
|
||||
color: Colors.white, size: 18),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(child: Text(state.message)),
|
||||
],
|
||||
@@ -86,8 +146,6 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
child: Scaffold(
|
||||
backgroundColor: AppTheme.warmWhite,
|
||||
body: SafeArea(
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
SliverFillRemaining(
|
||||
@@ -99,23 +157,61 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 28),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 48),
|
||||
_buildHeader(),
|
||||
const SizedBox(height: 32),
|
||||
_buildForm(context),
|
||||
const SizedBox(height: 24),
|
||||
const PrivacyNoticeCard(),
|
||||
const SizedBox(height: 32),
|
||||
_buildDemoHint(),
|
||||
const Spacer(),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
Center(
|
||||
child: Text(
|
||||
'Sistema Municipal de Recolección Residencial\nCelaya, Guanajuato',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 12, color: Colors.grey.shade600, height: 1.3),
|
||||
fontSize: 12,
|
||||
color: Colors.grey.shade600,
|
||||
height: 1.3),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
// Asegúrate de que este widget esté definido en tu proyecto o cámbialo por un placeholder
|
||||
// const ScheduleWarningBanner(),
|
||||
const SizedBox(height: 32),
|
||||
),
|
||||
const SizedBox(height: 48),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --- CAMPO: EMAIL / IDENTIFICADOR ---
|
||||
Widget _buildHeader() {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: const [
|
||||
Text('Bienvenido a WasteNotify',
|
||||
style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
|
||||
SizedBox(height: 8),
|
||||
Text('Inicia sesión para continuar',
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildForm(BuildContext context) {
|
||||
return Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _identifierController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
@@ -125,39 +221,40 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(12))),
|
||||
),
|
||||
validator: (value) =>
|
||||
(value == null || value.trim().isEmpty)
|
||||
validator: (value) => (value == null || value.trim().isEmpty)
|
||||
? 'Por favor, ingresa tus datos de acceso'
|
||||
: null,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// --- CAMPO: CONTRASEÑA ---
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Contraseña de Acceso',
|
||||
prefixIcon: const Icon(Icons.lock_outline_rounded),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscurePassword ? Icons.visibility_off : Icons.visibility),
|
||||
onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
|
||||
),
|
||||
border: const OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(12))),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_obscurePassword ? Icons.visibility : Icons.visibility_off),
|
||||
onPressed: () =>
|
||||
setState(() => _obscurePassword = !_obscurePassword),
|
||||
),
|
||||
),
|
||||
validator: (value) => (value == null || value.isEmpty)
|
||||
? 'Por favor, introduce tu contraseña'
|
||||
: null,
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// --- CONTENEDOR REACTIVO DE BOTONES ---
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) {
|
||||
final isLoading = state is AuthLoading;
|
||||
|
||||
return AnimatedContainer(
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
@@ -165,7 +262,8 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
? []
|
||||
: [
|
||||
BoxShadow(
|
||||
color: AppTheme.leafGreen.withOpacity(0.3),
|
||||
color:
|
||||
AppTheme.leafGreen.withValues(alpha: 0.3),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
@@ -175,38 +273,45 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
onPressed: isLoading ? null : () => _submit(context),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: isLoading
|
||||
? AppTheme.mintGreen.withOpacity(0.7)
|
||||
? AppTheme.mintGreen.withValues(alpha: 0.7)
|
||||
: AppTheme.leafGreen,
|
||||
disabledBackgroundColor: AppTheme.mintGreen.withOpacity(0.6),
|
||||
disabledBackgroundColor:
|
||||
AppTheme.mintGreen.withValues(alpha: 0.6),
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
child: isLoading
|
||||
? const CircularProgressIndicator(color: Colors.white)
|
||||
: const Text('Iniciar Sesión', style: TextStyle(color: Colors.white)),
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
color: Colors.white, strokeWidth: 2),
|
||||
)
|
||||
: const Text('Iniciar Sesión',
|
||||
style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
// 📍 BOTÓN DE REGISTRO CORREGIDO (child al final)
|
||||
TextButton(
|
||||
onPressed: () => context.push(AppRoutes.register),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: AppTheme.leafGreen,
|
||||
textStyle: const TextStyle(
|
||||
fontSize: 14, fontWeight: FontWeight.w500),
|
||||
),
|
||||
child: const Text('¿No tienes cuenta? Regístrate aquí'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const PrivacyNoticeCard(),
|
||||
const SizedBox(height: 32),
|
||||
_buildDemoHint(),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
} // 📍 Cierre de la función _buildForm
|
||||
|
||||
// Métodos auxiliares creados como placeholders para evitar errores de compilación
|
||||
Widget _buildHeader() => const Center(child: Text("WasteNotify", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)));
|
||||
Widget _buildDemoHint() => const Center(child: Text("Demo: ciudadano@ejemplo.com / password123", style: TextStyle(fontSize: 12)));
|
||||
}
|
||||
// Placeholders para evitar errores si no están definidos
|
||||
Widget _buildDemoHint() => const SizedBox.shrink();
|
||||
} // 📍 Cierre de la clase _LoginScreenState
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:math'; //
|
||||
import '../../../../core/network/mysql_service.dart'; // 📍 Ajusta las carpetas '../' según tu proyecto
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:flutter_application_1/features/auth/data/models/mock_waste_data.dart';
|
||||
@@ -11,11 +13,29 @@ class RegisterScreen extends StatefulWidget {
|
||||
|
||||
class _RegisterScreenState extends State<RegisterScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
String _selectedColonia = 'Centro';
|
||||
late String _selectedColonia;
|
||||
final _nameController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (MockWasteData.schedules.isNotEmpty) {
|
||||
_selectedColonia = MockWasteData.schedules.first.colonia;
|
||||
} else {
|
||||
_selectedColonia = '';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@@ -27,7 +47,8 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Icon(Icons.assignment_ind_outlined, size: 80, color: Colors.green),
|
||||
const Icon(Icons.assignment_ind_outlined,
|
||||
size: 80, color: Colors.green),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Regístrate para recibir avisos de recolección en tu zona',
|
||||
@@ -37,64 +58,133 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
const SizedBox(height: 24),
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
decoration: const InputDecoration(labelText: 'Nombre Completo', border: OutlineInputBorder()),
|
||||
validator: (v) => v!.isEmpty ? 'Ingresa tu nombre' : null,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nombre Completo',
|
||||
border: OutlineInputBorder()),
|
||||
validator: (v) =>
|
||||
v == null || v.isEmpty ? 'Ingresa tu nombre' : null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
decoration: const InputDecoration(labelText: 'Correo o Teléfono', border: OutlineInputBorder()),
|
||||
validator: (v) => v!.isEmpty ? 'Ingresa tus datos' : null,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Correo o Teléfono',
|
||||
border: OutlineInputBorder()),
|
||||
validator: (v) =>
|
||||
v == null || v.isEmpty ? 'Ingresa tus datos' : null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(labelText: 'Contraseña', border: OutlineInputBorder()),
|
||||
validator: (v) => v!.length < 6 ? 'Mínimo 6 caracteres' : null,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Contraseña', border: OutlineInputBorder()),
|
||||
validator: (v) =>
|
||||
v == null || v.length < 6 ? 'Mínimo 6 caracteres' : null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Dropdown para seleccionar la Colonia (Requisito MVP)
|
||||
DropdownButtonFormField<String>(
|
||||
value: _selectedColonia,
|
||||
decoration: const InputDecoration(labelText: 'Selecciona tu Colonia / Domicilio', border: OutlineInputBorder()),
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Selecciona tu Colonia / Domicilio',
|
||||
border: OutlineInputBorder()),
|
||||
items: MockWasteData.schedules.map((zone) {
|
||||
return DropdownMenuItem(value: zone.colonia, child: Text(zone.colonia));
|
||||
return DropdownMenuItem(
|
||||
value: zone.colonia, child: Text(zone.colonia));
|
||||
}).toList(),
|
||||
onChanged: (val) => setState(() => _selectedColonia = val!),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Mensajería Preventiva Legal
|
||||
Card(
|
||||
color: Colors.amber.shade50,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Text(
|
||||
'🔒 Privacidad Garantizada:\nAl registrar tu domicilio, tu cuenta operará bajo el principio de "Visión de Túnel". Solo verás alertas de tu sector. Está prohibido el rastreo de flotillas.',
|
||||
style: TextStyle(color: Colors.amber.shade900, fontSize: 13, fontWeight: FontWeight.bold),
|
||||
style: TextStyle(
|
||||
color: Colors.amber.shade900,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16), backgroundColor: Colors.green),
|
||||
onPressed: () {
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
backgroundColor: Colors.green),
|
||||
onPressed: () async {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
// Simulación de Registro Exitoso: Navega al Home enviando la colonia elegida
|
||||
try {
|
||||
print(
|
||||
'=== DEPURACIÓN: Iniciando proceso de registro ===');
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Cuenta creada con éxito (Modo Simulación)')),
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Conectando con la base de datos local...')),
|
||||
);
|
||||
|
||||
final conn = await MySqlService().getConnection();
|
||||
print(
|
||||
'=== DEPURACIÓN: ¡Conexión obtenida! Estado connected: ${conn.connected}');
|
||||
|
||||
print('=== DEPURACIÓN: Intentando ejecutar INSERT ===');
|
||||
final randomPhone =
|
||||
'461${1000000 + Random().nextInt(9000000)}'; // 📍 ENVIANDO LA COLONIA REAL A TU NUEVA COLUMNA DE MYSQL
|
||||
final result = await conn.execute(
|
||||
"INSERT INTO usuarios (email, telefono, contrasena_hash, rol, is_verified, colonia) VALUES (:email, :telefono, :contrasena_hash, :rol, :is_verified, :colonia)",
|
||||
{
|
||||
"email": _emailController.text.trim(),
|
||||
"telefono": randomPhone, // 📍 Genera un teléfono simulado para cumplir con el esquema de tu tabla
|
||||
"contrasena_hash": _passwordController.text,
|
||||
"rol": "Ciudadano",
|
||||
"is_verified": 1,
|
||||
"colonia":
|
||||
_selectedColonia, // 📍 Envía la colonia seleccionada en el Dropdown
|
||||
},
|
||||
);
|
||||
|
||||
print(
|
||||
'=== DEPURACIÓN: INSERT completado. Filas afectadas: ${result.affectedRows}');
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (result.affectedRows > BigInt.zero) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'¡Usuario guardado con éxito en MySQL Celaya!')),
|
||||
);
|
||||
context.go('/home?colonia=$_selectedColonia');
|
||||
} else {
|
||||
print(
|
||||
'=== DEPURACIÓN: El query se ejecutó pero devolvió 0 filas afectadas ===');
|
||||
}
|
||||
} catch (e, stacktrace) {
|
||||
print(
|
||||
'=== DEPURACIÓN: ¡CAPTURADO UN ERROR EN EL CATCH! ===');
|
||||
print('Detalle del error: $e');
|
||||
print(
|
||||
'Ubicación del fallo (Stacktrace): \n$stacktrace');
|
||||
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Error de conexión a MySQL: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
duration: const Duration(seconds: 5),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
child: const Text('Registrarse', style: TextStyle(color: Colors.white, fontSize: 16)),
|
||||
child: const Text('Registrarse',
|
||||
style: TextStyle(color: Colors.white, fontSize: 16)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ class PrivacyNoticeCard extends StatelessWidget {
|
||||
color: AppTheme.lightMint,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: AppTheme.mintGreen.withOpacity(0.3),
|
||||
color: AppTheme.mintGreen.withValues(alpha: 0.3),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
@@ -85,7 +85,7 @@ class _PrivacyPoint extends StatelessWidget {
|
||||
text,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: AppTheme.forestGreen.withOpacity(0.85),
|
||||
color: AppTheme.forestGreen.withValues(alpha: 0.85),
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
@@ -105,10 +105,10 @@ class ScheduleWarningBanner extends StatelessWidget {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.alertAmber.withOpacity(0.10),
|
||||
color: AppTheme.alertAmber.withValues(alpha: 0.10),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: AppTheme.alertAmber.withOpacity(0.35),
|
||||
color: AppTheme.alertAmber.withValues(alpha: 0.35),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
|
||||
32
pubspec.lock
32
pubspec.lock
@@ -33,6 +33,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
buffer:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: buffer
|
||||
sha256: "389da2ec2c16283c8787e0adaede82b1842102f8c8aae2f49003a766c5c6b3d1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.3"
|
||||
characters:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -57,6 +65,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.19.0"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: crypto
|
||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.7"
|
||||
cupertino_icons:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -304,6 +320,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
mysql_client:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: mysql_client
|
||||
sha256: "6a0fdcbe3e0721c637f97ad24649be2f70dbce2b21ede8f962910e640f753fc2"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.0.27"
|
||||
nested:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -509,6 +533,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.10.1"
|
||||
tuple:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: tuple
|
||||
sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.2"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -32,6 +32,7 @@ dependencies:
|
||||
flutter_map: ^6.2.1
|
||||
latlong2: ^0.9.1
|
||||
flutter_local_notifications: ^19.5.0
|
||||
mysql_client: ^0.0.27
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import 'package:flutter_test/flutter_test.dart';
|
||||
// Use a local test app to avoid depending on external package imports
|
||||
// which may not exist in the test environment.
|
||||
class MyApp extends StatefulWidget {
|
||||
const MyApp({Key? key}) : super(key: key);
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
State<MyApp> createState() => _MyAppState();
|
||||
|
||||
Reference in New Issue
Block a user