123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247 |
- import 'package:flutter/material.dart';
- import 'package:provider/provider.dart';
- import '../../models/models.dart';
- import '../../themes/themes.dart';
- import '../../viewmodels/viewmodels.dart';
- import '../../widgets/widgets.dart';
- import '../home/home_screen.dart';
- class LoginScreen extends StatefulWidget {
- const LoginScreen({Key? key}) : super(key: key);
- @override
- State<LoginScreen> createState() => _LoginScreenState();
- }
- class _LoginScreenState extends State<LoginScreen> {
- final _correo = TextEditingController();
- final _contrasena = TextEditingController();
- Sucursal? _selectedSucursal;
- @override
- void dispose() {
- super.dispose();
- _correo.dispose();
- _contrasena.dispose();
- }
- @override
- void initState() {
- super.initState();
- // Verifica la sesión almacenada
- WidgetsBinding.instance.addPostFrameCallback((_) {
- final loginViewModel =
- Provider.of<LoginViewModel>(context, listen: false);
- Provider.of<PermisoViewModel>(context, listen: false)
- .sincronizarPermisos();
- Provider.of<UsuarioViewModel>(context, listen: false)
- .sincronizarUsuarios();
- // Verificar la sesión
- loginViewModel.checkSession().then((_) {
- if (loginViewModel.status == Status.authenticated) {
- print("Sesión activa detectada, redirigiendo al HomeScreen.");
- Navigator.pushReplacement(
- context,
- MaterialPageRoute(builder: (context) => const HomeScreen()),
- );
- } else {
- print("No se detectó sesión, mostrando la pantalla de login.");
- final sucursalViewModel =
- Provider.of<SucursalViewModel>(context, listen: false);
- sucursalViewModel.sincronizarSucursales().then((_) {
- setState(() {
- final sucursales = sucursalViewModel.sucursales;
- _selectedSucursal = sucursales.firstWhere(
- (sucursal) => sucursal.seleccionado == 1,
- orElse: () =>
- sucursales.isNotEmpty ? sucursales[0] : Sucursal(),
- );
- });
- });
- }
- });
- });
- }
- @override
- Widget build(BuildContext context) {
- final loginViewModel = Provider.of<LoginViewModel>(context);
- // Mostrar la pantalla de carga `Cargando` mientras verifica la sesión
- if (loginViewModel.isLoading) {
- return const Cargando();
- }
- final size = MediaQuery.sizeOf(context);
- final sucursalViewModel = Provider.of<SucursalViewModel>(context);
- final sucursales = sucursalViewModel.sucursales;
- final obscureText = loginViewModel.obscureText;
- final errores = loginViewModel.errores;
- return Scaffold(
- backgroundColor: const Color.fromRGBO(245, 245, 245, 1),
- body: SingleChildScrollView(
- child: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- SizedBox(height: size.width < 1200 ? 20 : 100),
- const Image(
- image: AssetImage('assets/JoshiLogoHorizontal.png'),
- height: 250,
- ),
- const Text(
- 'Inicie sesión para acceder al sistema',
- style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
- textAlign: TextAlign.center,
- ),
- const SizedBox(height: 20),
- // Campo de correo
- SizedBox(
- width: size.width < 1200 ? size.width : size.width * .35,
- child: Card(
- elevation: 5,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(15)),
- child: Padding(
- padding: const EdgeInsets.all(15),
- child: Column(
- children: [
- AppDropdownModel<Sucursal>(
- etiqueta: 'Seleccione una sucursal',
- hint: 'Elija una sucursal',
- selectedValue: _selectedSucursal,
- onChanged: (Sucursal? newValue) {
- setState(() {
- _selectedSucursal = newValue;
- });
- },
- items: sucursales.map((Sucursal sucursal) {
- return DropdownMenuItem<Sucursal>(
- value: sucursal,
- child: Text(
- sucursal.nombre ?? '',
- style: const TextStyle(color: Colors.black),
- ),
- );
- }).toList(),
- ),
- const SizedBox(height: 5),
- AppTextField(
- autofillHints: [AutofillHints.username],
- prefixIcon: const Icon(Icons.mail),
- etiqueta: 'Correo electrónico',
- hintText: 'Introduzca su correo electrónico',
- errorText: errores?['correo'],
- controller: _correo,
- keyboardType: TextInputType.emailAddress,
- ),
- const SizedBox(height: 5),
- AppTextField(
- prefixIcon: const Icon(Icons.lock),
- obscureText: obscureText,
- etiqueta: 'Contraseña',
- hintText: 'Introduzca su contraseña',
- errorText: errores?['contrasena'],
- controller: _contrasena,
- suffixIcon: IconButton(
- onPressed: () {
- loginViewModel.showPassword();
- },
- icon: obscureText
- ? const Icon(Icons.remove_red_eye_outlined)
- : const Icon(Icons.remove_red_eye),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- const SizedBox(height: 20),
- // Botón de login
- Align(
- alignment: Alignment.center,
- child: SizedBox(
- height: 75,
- width: 380,
- child: ElevatedButton(
- style: ButtonStyle(
- shape: MaterialStatePropertyAll(
- RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(10),
- ),
- ),
- backgroundColor:
- MaterialStatePropertyAll(AppTheme.secondary),
- ),
- onPressed: () async {
- await loginViewModel.login(
- _correo.text, _contrasena.text);
- if (loginViewModel.status == Status.authenticated) {
- if (_selectedSucursal != null) {
- await sucursalViewModel
- .setSelectedSucursal(_selectedSucursal!);
- }
- Navigator.pushReplacement(
- context,
- MaterialPageRoute(
- builder: (context) => const HomeScreen()),
- );
- } else {
- String mensaje = "";
- if (loginViewModel.errores?["correo"] != null) {
- mensaje += "\n${loginViewModel.errores!["correo"]}";
- }
- if (mensaje.isNotEmpty && context.mounted) {
- return showDialog(
- context: context,
- builder: (context) {
- return AlertDialog(
- title: const Text("Alerta"),
- content: Text(mensaje),
- actions: [
- Row(children: [
- Expanded(
- child: TextButton(
- onPressed: () async {
- Navigator.pop(context);
- },
- child: const Text('Continuar'),
- ))
- ])
- ],
- );
- },
- );
- }
- }
- },
- child: const Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Text(
- 'Iniciar Sesión',
- style: TextStyle(fontSize: 18, color: Colors.white),
- ),
- ],
- ),
- ),
- ),
- ),
- const SizedBox(height: 20),
- ],
- ),
- ),
- ),
- );
- }
- }
|