initial commit 2
This commit is contained in:
106
lib/app.dart
Normal file
106
lib/app.dart
Normal file
@@ -0,0 +1,106 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'models/auth_session.dart';
|
||||
import 'screens/auth_screen.dart';
|
||||
import 'screens/dashboard_screen.dart';
|
||||
import 'services/address_repository.dart';
|
||||
import 'services/auth_repository.dart';
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({
|
||||
super.key,
|
||||
AuthRepository? authRepository,
|
||||
AddressRepository? addressRepository,
|
||||
this.enableLiveFeatures = true,
|
||||
}) : _authRepository = authRepository ?? const HttpAuthRepository(),
|
||||
_addressRepository = addressRepository ?? const HttpAddressRepository();
|
||||
|
||||
final AuthRepository _authRepository;
|
||||
final AddressRepository _addressRepository;
|
||||
final bool enableLiveFeatures;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: 'Acceso',
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF0F766E)),
|
||||
useMaterial3: true,
|
||||
),
|
||||
home: AuthBootstrap(
|
||||
authRepository: _authRepository,
|
||||
addressRepository: _addressRepository,
|
||||
enableLiveFeatures: enableLiveFeatures,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AuthBootstrap extends StatefulWidget {
|
||||
const AuthBootstrap({
|
||||
super.key,
|
||||
required this.authRepository,
|
||||
required this.addressRepository,
|
||||
this.enableLiveFeatures = true,
|
||||
});
|
||||
|
||||
final AuthRepository authRepository;
|
||||
final AddressRepository addressRepository;
|
||||
final bool enableLiveFeatures;
|
||||
|
||||
@override
|
||||
State<AuthBootstrap> createState() => _AuthBootstrapState();
|
||||
}
|
||||
|
||||
class _AuthBootstrapState extends State<AuthBootstrap> {
|
||||
late final Future<AuthSession?> _sessionFuture;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_sessionFuture = widget.authRepository.restoreSession();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<AuthSession?>(
|
||||
future: _sessionFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return const _LoadingView();
|
||||
}
|
||||
|
||||
final session = snapshot.data;
|
||||
if (session != null) {
|
||||
return DashboardScreen(
|
||||
authRepository: widget.authRepository,
|
||||
addressRepository: widget.addressRepository,
|
||||
session: session,
|
||||
savedAddress: null,
|
||||
enableLiveFeatures: widget.enableLiveFeatures,
|
||||
);
|
||||
}
|
||||
|
||||
return AuthScreen(
|
||||
authRepository: widget.authRepository,
|
||||
addressRepository: widget.addressRepository,
|
||||
enableLiveFeatures: widget.enableLiveFeatures,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LoadingView extends StatelessWidget {
|
||||
const _LoadingView();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Scaffold(
|
||||
body: Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
6
lib/app_config.dart
Normal file
6
lib/app_config.dart
Normal file
@@ -0,0 +1,6 @@
|
||||
class AppConfig {
|
||||
static const String apiBaseUrl = String.fromEnvironment(
|
||||
'API_BASE_URL',
|
||||
defaultValue: 'http://10.77.234.29:3000',
|
||||
);
|
||||
}
|
||||
9
lib/main.dart
Normal file
9
lib/main.dart
Normal file
@@ -0,0 +1,9 @@
|
||||
export 'app.dart';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'app.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
19
lib/models/address_entry.dart
Normal file
19
lib/models/address_entry.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
class AddressEntry {
|
||||
const AddressEntry({
|
||||
required this.houseNumber,
|
||||
required this.colonia,
|
||||
required this.street,
|
||||
});
|
||||
|
||||
final String houseNumber;
|
||||
final String colonia;
|
||||
final String street;
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return <String, dynamic>{
|
||||
'houseNumber': houseNumber,
|
||||
'colonia': colonia,
|
||||
'street': street,
|
||||
};
|
||||
}
|
||||
}
|
||||
22
lib/models/address_record.dart
Normal file
22
lib/models/address_record.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
class AddressRecord {
|
||||
const AddressRecord({
|
||||
required this.id,
|
||||
required this.houseNumber,
|
||||
required this.colonia,
|
||||
required this.street,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String houseNumber;
|
||||
final String colonia;
|
||||
final String street;
|
||||
|
||||
factory AddressRecord.fromJson(Map<String, dynamic> json) {
|
||||
return AddressRecord(
|
||||
id: (json['id'] as num).toInt(),
|
||||
houseNumber: json['house_number']?.toString() ?? json['houseNumber']?.toString() ?? '',
|
||||
colonia: json['colonia']?.toString() ?? '',
|
||||
street: json['street']?.toString() ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
11
lib/models/auth_session.dart
Normal file
11
lib/models/auth_session.dart
Normal file
@@ -0,0 +1,11 @@
|
||||
class AuthSession {
|
||||
const AuthSession({
|
||||
required this.token,
|
||||
required this.email,
|
||||
required this.displayName,
|
||||
});
|
||||
|
||||
final String token;
|
||||
final String email;
|
||||
final String displayName;
|
||||
}
|
||||
255
lib/screens/address_screen.dart
Normal file
255
lib/screens/address_screen.dart
Normal file
@@ -0,0 +1,255 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app_config.dart';
|
||||
import '../models/address_entry.dart';
|
||||
import '../models/auth_session.dart';
|
||||
import '../services/auth_repository.dart';
|
||||
import '../services/address_repository.dart';
|
||||
import 'dashboard_screen.dart';
|
||||
|
||||
class AddressScreen extends StatefulWidget {
|
||||
const AddressScreen({
|
||||
super.key,
|
||||
required this.authRepository,
|
||||
required this.addressRepository,
|
||||
required this.session,
|
||||
this.enableLiveFeatures = true,
|
||||
});
|
||||
|
||||
final AuthRepository authRepository;
|
||||
final AddressRepository addressRepository;
|
||||
final AuthSession session;
|
||||
final bool enableLiveFeatures;
|
||||
|
||||
@override
|
||||
State<AddressScreen> createState() => _AddressScreenState();
|
||||
}
|
||||
|
||||
class _AddressScreenState extends State<AddressScreen> {
|
||||
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
|
||||
final TextEditingController _houseNumberController = TextEditingController();
|
||||
final TextEditingController _coloniaController = TextEditingController();
|
||||
final TextEditingController _streetController = TextEditingController();
|
||||
|
||||
bool _isSaving = false;
|
||||
String? _errorMessage;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_houseNumberController.dispose();
|
||||
_coloniaController.dispose();
|
||||
_streetController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _saveAddress() async {
|
||||
if (!(_formKey.currentState?.validate() ?? false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_isSaving = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
await widget.addressRepository.saveAddress(
|
||||
session: widget.session,
|
||||
address: AddressEntry(
|
||||
houseNumber: _houseNumberController.text.trim(),
|
||||
colonia: _coloniaController.text.trim(),
|
||||
street: _streetController.text.trim(),
|
||||
),
|
||||
);
|
||||
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
Navigator.of(context).pushAndRemoveUntil(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => DashboardScreen(
|
||||
authRepository: widget.authRepository,
|
||||
addressRepository: widget.addressRepository,
|
||||
session: widget.session,
|
||||
savedAddress: AddressEntry(
|
||||
houseNumber: _houseNumberController.text.trim(),
|
||||
colonia: _coloniaController.text.trim(),
|
||||
street: _streetController.text.trim(),
|
||||
),
|
||||
enableLiveFeatures: widget.enableLiveFeatures,
|
||||
),
|
||||
),
|
||||
(route) => false,
|
||||
);
|
||||
} on AddressException catch (error) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_errorMessage = error.message;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_errorMessage = 'No se pudo guardar la dirección. Revisa el backend.';
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isSaving = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Container(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFFF8FAFC), Color(0xFFE2E8F0), Color(0xFFCCFBF1)],
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 520),
|
||||
child: Card(
|
||||
elevation: 12,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'Dirección',
|
||||
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Ingresa la dirección de tu casa y se enviará al backend para guardarla en PostgreSQL.',
|
||||
style: TextStyle(color: Colors.grey.shade700, height: 1.4),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
if (_errorMessage != null) ...[
|
||||
_AddressStatusBanner(message: _errorMessage!),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _houseNumberController,
|
||||
keyboardType: TextInputType.text,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Número de casa',
|
||||
prefixIcon: Icon(Icons.home_outlined),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Ingresa el número de casa';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _coloniaController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Colonia',
|
||||
prefixIcon: Icon(Icons.location_city_outlined),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Ingresa la colonia';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _streetController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Calle',
|
||||
prefixIcon: Icon(Icons.signpost_outlined),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Ingresa la calle';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 52,
|
||||
child: FilledButton(
|
||||
onPressed: _isSaving ? null : _saveAddress,
|
||||
child: _isSaving
|
||||
? const SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white),
|
||||
)
|
||||
: const Text('Guardar dirección'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'Base URL configurada: ${AppConfig.apiBaseUrl}',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AddressStatusBanner extends StatelessWidget {
|
||||
const _AddressStatusBanner({required this.message});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFEE2E2),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFFCA5A5)),
|
||||
),
|
||||
child: Text(
|
||||
message,
|
||||
style: const TextStyle(color: Color(0xFF991B1B), height: 1.35),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
461
lib/screens/auth_screen.dart
Normal file
461
lib/screens/auth_screen.dart
Normal file
@@ -0,0 +1,461 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app_config.dart';
|
||||
import '../models/auth_session.dart';
|
||||
import '../services/address_repository.dart';
|
||||
import '../services/auth_repository.dart';
|
||||
import 'address_screen.dart';
|
||||
|
||||
class AuthScreen extends StatefulWidget {
|
||||
const AuthScreen({
|
||||
super.key,
|
||||
required this.authRepository,
|
||||
required this.addressRepository,
|
||||
this.enableLiveFeatures = true,
|
||||
});
|
||||
|
||||
final AuthRepository authRepository;
|
||||
final AddressRepository addressRepository;
|
||||
final bool enableLiveFeatures;
|
||||
|
||||
@override
|
||||
State<AuthScreen> createState() => _AuthScreenState();
|
||||
}
|
||||
|
||||
class _AuthScreenState extends State<AuthScreen> {
|
||||
final GlobalKey<FormState> _loginFormKey = GlobalKey<FormState>();
|
||||
final GlobalKey<FormState> _registerFormKey = GlobalKey<FormState>();
|
||||
final TextEditingController _loginEmailController = TextEditingController();
|
||||
final TextEditingController _loginPasswordController = TextEditingController();
|
||||
final TextEditingController _registerNameController = TextEditingController();
|
||||
final TextEditingController _registerEmailController = TextEditingController();
|
||||
final TextEditingController _registerPasswordController = TextEditingController();
|
||||
final TextEditingController _registerConfirmPasswordController = TextEditingController();
|
||||
|
||||
bool _isLoading = false;
|
||||
String? _errorMessage;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_loginEmailController.dispose();
|
||||
_loginPasswordController.dispose();
|
||||
_registerNameController.dispose();
|
||||
_registerEmailController.dispose();
|
||||
_registerPasswordController.dispose();
|
||||
_registerConfirmPasswordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _signIn() async {
|
||||
if (!(_loginFormKey.currentState?.validate() ?? false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await _submit(() {
|
||||
return widget.authRepository.signIn(
|
||||
email: _loginEmailController.text.trim(),
|
||||
password: _loginPasswordController.text,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _signUp() async {
|
||||
if (!(_registerFormKey.currentState?.validate() ?? false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await _submit(() {
|
||||
return widget.authRepository.signUp(
|
||||
name: _registerNameController.text.trim(),
|
||||
email: _registerEmailController.text.trim(),
|
||||
password: _registerPasswordController.text,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _submit(Future<AuthSession> Function() action) async {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final session = await action();
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pushReplacement(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => AddressScreen(
|
||||
authRepository: widget.authRepository,
|
||||
addressRepository: widget.addressRepository,
|
||||
session: session,
|
||||
enableLiveFeatures: widget.enableLiveFeatures,
|
||||
),
|
||||
),
|
||||
);
|
||||
} on AuthException catch (error) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_errorMessage = error.message;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_errorMessage = 'No se pudo completar la operación. Verifica el backend y vuelve a intentar.';
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Container(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFF06141B), Color(0xFF0F766E), Color(0xFFE2E8F0)],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 440),
|
||||
child: Card(
|
||||
elevation: 18,
|
||||
color: Colors.white.withValues(alpha: 0.94),
|
||||
shadowColor: Colors.black26,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: DefaultTabController(
|
||||
length: 2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 72,
|
||||
height: 72,
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF0F766E).withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: const Icon(Icons.lock_outline, size: 36, color: Color(0xFF0F766E)),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const Text(
|
||||
'Bienvenido',
|
||||
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Inicia sesión o crea una cuenta para continuar. Luego irás a la pantalla Dirección.',
|
||||
style: TextStyle(color: Colors.grey.shade700, height: 1.4),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFF1F5F9),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: TabBar(
|
||||
onTap: (_) {
|
||||
setState(() {
|
||||
_errorMessage = null;
|
||||
});
|
||||
},
|
||||
indicatorSize: TabBarIndicatorSize.tab,
|
||||
dividerColor: Colors.transparent,
|
||||
indicator: BoxDecoration(
|
||||
color: const Color(0xFF0F766E),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
labelColor: Colors.white,
|
||||
unselectedLabelColor: Colors.grey.shade700,
|
||||
tabs: const [
|
||||
Tab(text: 'Entrar'),
|
||||
Tab(text: 'Crear cuenta'),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
if (_errorMessage != null) ...[
|
||||
_AuthStatusBanner(message: _errorMessage!),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
SizedBox(
|
||||
height: 200,
|
||||
child: TabBarView(
|
||||
children: [
|
||||
_LoginForm(
|
||||
formKey: _loginFormKey,
|
||||
emailController: _loginEmailController,
|
||||
passwordController: _loginPasswordController,
|
||||
onSubmit: _signIn,
|
||||
isLoading: _isLoading,
|
||||
),
|
||||
_RegisterForm(
|
||||
formKey: _registerFormKey,
|
||||
nameController: _registerNameController,
|
||||
emailController: _registerEmailController,
|
||||
passwordController: _registerPasswordController,
|
||||
confirmPasswordController: _registerConfirmPasswordController,
|
||||
onSubmit: _signUp,
|
||||
isLoading: _isLoading,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'Base URL configurada: ${AppConfig.apiBaseUrl}',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LoginForm extends StatelessWidget {
|
||||
const _LoginForm({
|
||||
required this.formKey,
|
||||
required this.emailController,
|
||||
required this.passwordController,
|
||||
required this.onSubmit,
|
||||
required this.isLoading,
|
||||
});
|
||||
|
||||
final GlobalKey<FormState> formKey;
|
||||
final TextEditingController emailController;
|
||||
final TextEditingController passwordController;
|
||||
final Future<void> Function() onSubmit;
|
||||
final bool isLoading;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Form(
|
||||
key: formKey,
|
||||
child: Column(
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Correo electrónico',
|
||||
prefixIcon: Icon(Icons.email_outlined),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Ingresa tu correo';
|
||||
}
|
||||
if (!value.contains('@')) {
|
||||
return 'Ingresa un correo válido';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: passwordController,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Contraseña',
|
||||
prefixIcon: Icon(Icons.lock_outline),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Ingresa tu contraseña';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
return 'Usa al menos 6 caracteres';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 52,
|
||||
child: FilledButton(
|
||||
onPressed: isLoading ? null : onSubmit,
|
||||
child: isLoading
|
||||
? const SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white),
|
||||
)
|
||||
: const Text('Ingresar'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RegisterForm extends StatelessWidget {
|
||||
const _RegisterForm({
|
||||
required this.formKey,
|
||||
required this.nameController,
|
||||
required this.emailController,
|
||||
required this.passwordController,
|
||||
required this.confirmPasswordController,
|
||||
required this.onSubmit,
|
||||
required this.isLoading,
|
||||
});
|
||||
|
||||
final GlobalKey<FormState> formKey;
|
||||
final TextEditingController nameController;
|
||||
final TextEditingController emailController;
|
||||
final TextEditingController passwordController;
|
||||
final TextEditingController confirmPasswordController;
|
||||
final Future<void> Function() onSubmit;
|
||||
final bool isLoading;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Form(
|
||||
key: formKey,
|
||||
child: ListView(
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: nameController,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nombre',
|
||||
prefixIcon: Icon(Icons.person_outline),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Ingresa tu nombre';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Correo electrónico',
|
||||
prefixIcon: Icon(Icons.email_outlined),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Ingresa tu correo';
|
||||
}
|
||||
if (!value.contains('@')) {
|
||||
return 'Ingresa un correo válido';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: passwordController,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Contraseña',
|
||||
prefixIcon: Icon(Icons.lock_outline),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Ingresa una contraseña';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
return 'Usa al menos 6 caracteres';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: confirmPasswordController,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Confirmar contraseña',
|
||||
prefixIcon: Icon(Icons.lock_reset_outlined),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Confirma tu contraseña';
|
||||
}
|
||||
if (value != passwordController.text) {
|
||||
return 'Las contraseñas no coinciden';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 52,
|
||||
child: FilledButton(
|
||||
onPressed: isLoading ? null : onSubmit,
|
||||
child: isLoading
|
||||
? const SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white),
|
||||
)
|
||||
: const Text('Registrarme'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AuthStatusBanner extends StatelessWidget {
|
||||
const _AuthStatusBanner({required this.message});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFEE2E2),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFFCA5A5)),
|
||||
),
|
||||
child: Text(
|
||||
message,
|
||||
style: const TextStyle(color: Color(0xFF991B1B), height: 1.35),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
943
lib/screens/dashboard_screen.dart
Normal file
943
lib/screens/dashboard_screen.dart
Normal file
@@ -0,0 +1,943 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_map/flutter_map.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import 'package:table_calendar/table_calendar.dart';
|
||||
|
||||
import '../models/address_entry.dart';
|
||||
import '../models/address_record.dart';
|
||||
import '../models/auth_session.dart';
|
||||
import '../services/address_repository.dart';
|
||||
import '../services/auth_repository.dart';
|
||||
import 'auth_screen.dart';
|
||||
|
||||
class DashboardScreen extends StatefulWidget {
|
||||
const DashboardScreen({
|
||||
super.key,
|
||||
required this.authRepository,
|
||||
required this.addressRepository,
|
||||
required this.session,
|
||||
this.savedAddress,
|
||||
this.enableLiveFeatures = true,
|
||||
});
|
||||
|
||||
final AuthRepository authRepository;
|
||||
final AddressRepository addressRepository;
|
||||
final AuthSession session;
|
||||
final AddressEntry? savedAddress;
|
||||
final bool enableLiveFeatures;
|
||||
|
||||
@override
|
||||
State<DashboardScreen> createState() => _DashboardScreenState();
|
||||
}
|
||||
|
||||
class _DashboardScreenState extends State<DashboardScreen> {
|
||||
final MapController _mapController = MapController();
|
||||
final TextEditingController _calendarNoteController = TextEditingController();
|
||||
final TextEditingController _newHouseNumberController = TextEditingController();
|
||||
final TextEditingController _newColoniaController = TextEditingController();
|
||||
final TextEditingController _newStreetController = TextEditingController();
|
||||
|
||||
final List<_AppNotification> _notifications = <_AppNotification>[];
|
||||
final Map<DateTime, String> _calendarNotes = <DateTime, String>{};
|
||||
final Random _random = Random();
|
||||
|
||||
int _selectedIndex = 0;
|
||||
LatLng _center = const LatLng(19.4326, -99.1332);
|
||||
bool _isLoadingLocation = true;
|
||||
bool _showLiveFeatures = true;
|
||||
String? _locationError;
|
||||
Timer? _truckTimer;
|
||||
LatLng? _truckPosition;
|
||||
bool _truckVisible = false;
|
||||
|
||||
bool _loadingAddresses = true;
|
||||
String? _addressesError;
|
||||
List<AddressRecord> _addresses = <AddressRecord>[];
|
||||
|
||||
DateTime _focusedDay = DateTime.now();
|
||||
DateTime? _selectedDay;
|
||||
CalendarFormat _calendarFormat = CalendarFormat.month;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_showLiveFeatures = widget.enableLiveFeatures;
|
||||
if (!_showLiveFeatures) {
|
||||
_isLoadingLocation = false;
|
||||
_loadingAddresses = false;
|
||||
_seedTruckSimulation();
|
||||
return;
|
||||
}
|
||||
|
||||
unawaited(_loadLocation());
|
||||
unawaited(_loadAddresses());
|
||||
_startTruckSimulation();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_truckTimer?.cancel();
|
||||
_calendarNoteController.dispose();
|
||||
_newHouseNumberController.dispose();
|
||||
_newColoniaController.dispose();
|
||||
_newStreetController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
DateTime _normalizeDay(DateTime day) => DateTime(day.year, day.month, day.day);
|
||||
|
||||
void _addNotification(String message) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_notifications.insert(0, _AppNotification(message: message, timestamp: DateTime.now()));
|
||||
});
|
||||
}
|
||||
|
||||
void _seedTruckSimulation() {
|
||||
final visible = _random.nextBool();
|
||||
_truckVisible = visible;
|
||||
_truckPosition = _truckOffsetFromCenter(_random.nextDouble() * 20.0);
|
||||
_notifications.add(
|
||||
_AppNotification(
|
||||
message: visible ? 'El camión de basura apareció cerca de tu ubicación.' : 'El camión de basura está fuera de rango.',
|
||||
timestamp: DateTime.now(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _loadLocation() async {
|
||||
try {
|
||||
final permission = await Geolocator.checkPermission();
|
||||
var currentPermission = permission;
|
||||
if (currentPermission == LocationPermission.denied) {
|
||||
currentPermission = await Geolocator.requestPermission();
|
||||
}
|
||||
|
||||
if (currentPermission == LocationPermission.denied || currentPermission == LocationPermission.deniedForever) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_locationError = 'Permiso de ubicación no concedido. Mostrando mapa por defecto.';
|
||||
_isLoadingLocation = false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
|
||||
final newCenter = LatLng(position.latitude, position.longitude);
|
||||
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_center = newCenter;
|
||||
_isLoadingLocation = false;
|
||||
_locationError = null;
|
||||
});
|
||||
|
||||
_mapController.move(newCenter, 15);
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_locationError = 'No se pudo obtener la ubicación actual. Se usó una referencia por defecto.';
|
||||
_isLoadingLocation = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadAddresses() async {
|
||||
try {
|
||||
final addresses = await widget.addressRepository.getMyAddresses(session: widget.session);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_addresses = addresses;
|
||||
_loadingAddresses = false;
|
||||
_addressesError = null;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_addressesError = error.toString();
|
||||
_loadingAddresses = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _startTruckSimulation() {
|
||||
_truckTimer?.cancel();
|
||||
_truckTimer = Timer.periodic(const Duration(seconds: 4), (_) {
|
||||
final distanceMeters = _random.nextDouble() * 40.0;
|
||||
final newTruckPosition = _truckOffsetFromCenter(distanceMeters);
|
||||
final wasVisible = _truckVisible;
|
||||
final isVisible = distanceMeters <= 20.0;
|
||||
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_truckPosition = newTruckPosition;
|
||||
_truckVisible = isVisible;
|
||||
});
|
||||
|
||||
if (isVisible != wasVisible) {
|
||||
_addNotification(
|
||||
isVisible
|
||||
? 'El camión de basura apareció a ${distanceMeters.toStringAsFixed(1)} m.'
|
||||
: 'El camión de basura salió del rango visible.',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
LatLng _truckOffsetFromCenter(double distanceMeters) {
|
||||
final angle = _random.nextDouble() * 2 * pi;
|
||||
final metersPerDegreeLat = 111320.0;
|
||||
final metersPerDegreeLng = 111320.0 * cos(_center.latitude * pi / 180.0).abs().clamp(0.2, 1.0);
|
||||
final deltaLat = (distanceMeters * cos(angle)) / metersPerDegreeLat;
|
||||
final deltaLng = (distanceMeters * sin(angle)) / metersPerDegreeLng;
|
||||
return LatLng(_center.latitude + deltaLat, _center.longitude + deltaLng);
|
||||
}
|
||||
|
||||
Future<void> _logOut(BuildContext context) async {
|
||||
await widget.authRepository.signOut();
|
||||
if (!context.mounted) {
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pushAndRemoveUntil(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => AuthScreen(
|
||||
authRepository: widget.authRepository,
|
||||
addressRepository: widget.addressRepository,
|
||||
),
|
||||
),
|
||||
(route) => false,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _saveCalendarNote() async {
|
||||
final note = _calendarNoteController.text.trim();
|
||||
if (note.isEmpty || _selectedDay == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final normalizedDay = _normalizeDay(_selectedDay!);
|
||||
setState(() {
|
||||
_calendarNotes[normalizedDay] = note;
|
||||
});
|
||||
_calendarNoteController.clear();
|
||||
_addNotification('Se guardó texto en el calendario para ${_selectedDay!.day}/${_selectedDay!.month}.');
|
||||
}
|
||||
|
||||
Future<void> _saveNewAddress() async {
|
||||
if (_newHouseNumberController.text.trim().isEmpty ||
|
||||
_newColoniaController.text.trim().isEmpty ||
|
||||
_newStreetController.text.trim().isEmpty) {
|
||||
_addNotification('Completa la nueva dirección antes de guardarla.');
|
||||
return;
|
||||
}
|
||||
|
||||
final newAddress = AddressEntry(
|
||||
houseNumber: _newHouseNumberController.text.trim(),
|
||||
colonia: _newColoniaController.text.trim(),
|
||||
street: _newStreetController.text.trim(),
|
||||
);
|
||||
|
||||
try {
|
||||
await widget.addressRepository.saveAddress(session: widget.session, address: newAddress);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_addresses = <AddressRecord>[
|
||||
AddressRecord(
|
||||
id: DateTime.now().millisecondsSinceEpoch,
|
||||
houseNumber: newAddress.houseNumber,
|
||||
colonia: newAddress.colonia,
|
||||
street: newAddress.street,
|
||||
),
|
||||
..._addresses,
|
||||
];
|
||||
});
|
||||
_newHouseNumberController.clear();
|
||||
_newColoniaController.clear();
|
||||
_newStreetController.clear();
|
||||
_addNotification('Se agregó una nueva dirección a tu perfil.');
|
||||
} catch (error) {
|
||||
_addNotification('No se pudo guardar la nueva dirección: $error');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final pages = <Widget>[
|
||||
_MapSection(
|
||||
center: _center,
|
||||
truckPosition: _truckPosition,
|
||||
truckVisible: _truckVisible,
|
||||
isLoadingLocation: _isLoadingLocation,
|
||||
locationError: _locationError,
|
||||
mapController: _mapController,
|
||||
showTiles: _showLiveFeatures,
|
||||
address: widget.savedAddress,
|
||||
),
|
||||
_CalendarSection(
|
||||
focusedDay: _focusedDay,
|
||||
selectedDay: _selectedDay,
|
||||
calendarFormat: _calendarFormat,
|
||||
notes: _calendarNotes,
|
||||
noteController: _calendarNoteController,
|
||||
onSelectedDay: (day, focusedDay) {
|
||||
setState(() {
|
||||
_selectedDay = day;
|
||||
_focusedDay = focusedDay;
|
||||
});
|
||||
},
|
||||
onFormatChanged: (format) {
|
||||
setState(() {
|
||||
_calendarFormat = format;
|
||||
});
|
||||
},
|
||||
onPageChanged: (focusedDay) {
|
||||
_focusedDay = focusedDay;
|
||||
},
|
||||
onSaveNote: _saveCalendarNote,
|
||||
),
|
||||
_NotificationsSection(notifications: _notifications),
|
||||
_DataSection(
|
||||
session: widget.session,
|
||||
loadingAddresses: _loadingAddresses,
|
||||
addressesError: _addressesError,
|
||||
addresses: _addresses,
|
||||
houseNumberController: _newHouseNumberController,
|
||||
coloniaController: _newColoniaController,
|
||||
streetController: _newStreetController,
|
||||
onSaveAddress: _saveNewAddress,
|
||||
),
|
||||
];
|
||||
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
_UserHeader(
|
||||
session: widget.session,
|
||||
onLogout: () => _logOut(context),
|
||||
),
|
||||
Expanded(
|
||||
child: IndexedStack(
|
||||
index: _selectedIndex,
|
||||
children: pages,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
bottomNavigationBar: NavigationBar(
|
||||
selectedIndex: _selectedIndex,
|
||||
onDestinationSelected: (index) {
|
||||
setState(() {
|
||||
_selectedIndex = index;
|
||||
});
|
||||
},
|
||||
destinations: const [
|
||||
NavigationDestination(icon: Icon(Icons.my_location_outlined), selectedIcon: Icon(Icons.my_location), label: 'Mapa'),
|
||||
NavigationDestination(icon: Icon(Icons.calendar_month_outlined), selectedIcon: Icon(Icons.calendar_month), label: 'Calendario'),
|
||||
NavigationDestination(icon: Icon(Icons.notifications_outlined), selectedIcon: Icon(Icons.notifications), label: 'Avisos'),
|
||||
NavigationDestination(icon: Icon(Icons.input_outlined), selectedIcon: Icon(Icons.input), label: 'Datos'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _UserHeader extends StatelessWidget {
|
||||
const _UserHeader({required this.session, required this.onLogout});
|
||||
|
||||
final AuthSession session;
|
||||
final VoidCallback onLogout;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Colors.teal.shade900, Colors.teal.shade700],
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 24,
|
||||
backgroundColor: Colors.white.withValues(alpha: 0.18),
|
||||
child: Text(
|
||||
session.displayName.isNotEmpty ? session.displayName[0].toUpperCase() : 'U',
|
||||
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w800),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(session.displayName, style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w700)),
|
||||
Text(session.email, style: TextStyle(color: Colors.white.withValues(alpha: 0.85))),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: onLogout,
|
||||
icon: const Icon(Icons.logout, color: Colors.white),
|
||||
tooltip: 'Cerrar sesión',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MapSection extends StatelessWidget {
|
||||
const _MapSection({
|
||||
required this.center,
|
||||
required this.truckPosition,
|
||||
required this.truckVisible,
|
||||
required this.isLoadingLocation,
|
||||
required this.locationError,
|
||||
required this.mapController,
|
||||
required this.showTiles,
|
||||
required this.address,
|
||||
});
|
||||
|
||||
final LatLng center;
|
||||
final LatLng? truckPosition;
|
||||
final bool truckVisible;
|
||||
final bool isLoadingLocation;
|
||||
final String? locationError;
|
||||
final MapController mapController;
|
||||
final bool showTiles;
|
||||
final AddressEntry? address;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final markers = <Marker>[
|
||||
Marker(
|
||||
width: 60,
|
||||
height: 60,
|
||||
point: center,
|
||||
child: const Icon(Icons.person_pin_circle, size: 56, color: Colors.blue),
|
||||
),
|
||||
if (truckVisible && truckPosition != null)
|
||||
Marker(
|
||||
width: 60,
|
||||
height: 60,
|
||||
point: truckPosition!,
|
||||
child: const Icon(Icons.local_shipping, size: 50, color: Colors.red),
|
||||
),
|
||||
];
|
||||
|
||||
return Container(
|
||||
color: const Color(0xFFF8FAFC),
|
||||
child: Column(
|
||||
children: [
|
||||
if (locationError != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: _NoticeBanner(message: locationError!),
|
||||
),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
child: Stack(
|
||||
children: [
|
||||
if (showTiles)
|
||||
FlutterMap(
|
||||
mapController: mapController,
|
||||
options: MapOptions(
|
||||
initialCenter: center,
|
||||
initialZoom: 15,
|
||||
interactionOptions: const InteractionOptions(flags: InteractiveFlag.all),
|
||||
),
|
||||
children: [
|
||||
TileLayer(
|
||||
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
userAgentPackageName: 'flutter_application_1',
|
||||
),
|
||||
MarkerLayer(markers: markers),
|
||||
],
|
||||
)
|
||||
else
|
||||
_MapPlaceholder(
|
||||
center: center,
|
||||
truckVisible: truckVisible,
|
||||
truckPosition: truckPosition,
|
||||
),
|
||||
Positioned(
|
||||
top: 16,
|
||||
left: 16,
|
||||
right: 16,
|
||||
child: Card(
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('Mapa y camión', style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w800)),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
address == null
|
||||
? 'No hay una dirección guardada todavía.'
|
||||
: 'Dirección: ${address!.houseNumber}, ${address!.colonia}, ${address!.street}',
|
||||
style: TextStyle(color: Colors.grey.shade700),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
truckVisible ? 'El camión está dentro de 20 m.' : 'El camión está fuera de rango.',
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (isLoadingLocation)
|
||||
const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MapPlaceholder extends StatelessWidget {
|
||||
const _MapPlaceholder({
|
||||
required this.center,
|
||||
required this.truckVisible,
|
||||
required this.truckPosition,
|
||||
});
|
||||
|
||||
final LatLng center;
|
||||
final bool truckVisible;
|
||||
final LatLng? truckPosition;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: const Color(0xFFE2E8F0),
|
||||
alignment: Alignment.center,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.map_outlined, size: 72, color: Colors.teal),
|
||||
const SizedBox(height: 12),
|
||||
const Text('Mapa centrado en tu ubicación', style: TextStyle(fontWeight: FontWeight.w700)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Lat: ${center.latitude.toStringAsFixed(5)}, Lng: ${center.longitude.toStringAsFixed(5)}'),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
truckVisible && truckPosition != null
|
||||
? 'Camión visible cerca de ti'
|
||||
: 'Camión fuera del rango de 20 m',
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CalendarSection extends StatelessWidget {
|
||||
const _CalendarSection({
|
||||
required this.focusedDay,
|
||||
required this.selectedDay,
|
||||
required this.calendarFormat,
|
||||
required this.notes,
|
||||
required this.noteController,
|
||||
required this.onSelectedDay,
|
||||
required this.onFormatChanged,
|
||||
required this.onPageChanged,
|
||||
required this.onSaveNote,
|
||||
});
|
||||
|
||||
final DateTime focusedDay;
|
||||
final DateTime? selectedDay;
|
||||
final CalendarFormat calendarFormat;
|
||||
final Map<DateTime, String> notes;
|
||||
final TextEditingController noteController;
|
||||
final void Function(DateTime day, DateTime focusedDay) onSelectedDay;
|
||||
final void Function(CalendarFormat format) onFormatChanged;
|
||||
final void Function(DateTime focusedDay) onPageChanged;
|
||||
final Future<void> Function() onSaveNote;
|
||||
|
||||
DateTime _normalizeDay(DateTime day) => DateTime(day.year, day.month, day.day);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selectedNormalized = selectedDay == null ? null : _normalizeDay(selectedDay!);
|
||||
|
||||
return Container(
|
||||
color: const Color(0xFFF8FAFC),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
Card(
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
TableCalendar<String>(
|
||||
firstDay: DateTime.utc(2020, 1, 1),
|
||||
lastDay: DateTime.utc(2035, 12, 31),
|
||||
focusedDay: focusedDay,
|
||||
calendarFormat: calendarFormat,
|
||||
selectedDayPredicate: (day) => isSameDay(selectedDay, day),
|
||||
eventLoader: (day) => notes.containsKey(_normalizeDay(day)) ? <String>[notes[_normalizeDay(day)]!] : <String>[],
|
||||
onDaySelected: onSelectedDay,
|
||||
onFormatChanged: onFormatChanged,
|
||||
onPageChanged: onPageChanged,
|
||||
calendarBuilders: CalendarBuilders(
|
||||
defaultBuilder: (context, day, focusedDay) {
|
||||
final note = notes[_normalizeDay(day)];
|
||||
if (note == null) {
|
||||
return null;
|
||||
}
|
||||
return _CalendarDayCell(day: day, note: note, selected: false);
|
||||
},
|
||||
selectedBuilder: (context, day, focusedDay) {
|
||||
final note = notes[_normalizeDay(day)];
|
||||
return _CalendarDayCell(day: day, note: note, selected: true);
|
||||
},
|
||||
todayBuilder: (context, day, focusedDay) {
|
||||
final note = notes[_normalizeDay(day)];
|
||||
return _CalendarDayCell(day: day, note: note, selected: false, today: true);
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: noteController,
|
||||
maxLines: 2,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Texto del día',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton(
|
||||
onPressed: onSaveNote,
|
||||
child: const Text('Guardar texto y resaltar casilla'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
selectedNormalized == null
|
||||
? 'Selecciona un día para escribir.'
|
||||
: 'Día seleccionado: ${selectedNormalized.day}/${selectedNormalized.month}/${selectedNormalized.year}',
|
||||
style: TextStyle(color: Colors.grey.shade700),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CalendarDayCell extends StatelessWidget {
|
||||
const _CalendarDayCell({
|
||||
required this.day,
|
||||
required this.note,
|
||||
required this.selected,
|
||||
this.today = false,
|
||||
});
|
||||
|
||||
final DateTime day;
|
||||
final String? note;
|
||||
final bool selected;
|
||||
final bool today;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final backgroundColor = selected
|
||||
? Colors.teal.shade700
|
||||
: today
|
||||
? Colors.teal.shade100
|
||||
: Colors.white;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.all(4),
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
color: backgroundColor,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: note == null ? Colors.grey.shade300 : Colors.teal),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
'${day.day}',
|
||||
style: TextStyle(
|
||||
color: selected ? Colors.white : Colors.black,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
if (note != null) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
note!,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
color: selected ? Colors.white : Colors.teal.shade900,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NotificationsSection extends StatelessWidget {
|
||||
const _NotificationsSection({required this.notifications});
|
||||
|
||||
final List<_AppNotification> notifications;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: const Color(0xFFF8FAFC),
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: notifications.isEmpty ? 1 : notifications.length,
|
||||
itemBuilder: (context, index) {
|
||||
if (notifications.isEmpty) {
|
||||
return const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(top: 48),
|
||||
child: Text('Aquí aparecerán las notificaciones.'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final notification = notifications[index];
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.notifications_active, color: Colors.teal),
|
||||
title: Text(notification.message),
|
||||
subtitle: Text(
|
||||
'${notification.timestamp.hour.toString().padLeft(2, '0')}:${notification.timestamp.minute.toString().padLeft(2, '0')}',
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DataSection extends StatelessWidget {
|
||||
const _DataSection({
|
||||
required this.session,
|
||||
required this.loadingAddresses,
|
||||
required this.addressesError,
|
||||
required this.addresses,
|
||||
required this.houseNumberController,
|
||||
required this.coloniaController,
|
||||
required this.streetController,
|
||||
required this.onSaveAddress,
|
||||
});
|
||||
|
||||
final AuthSession session;
|
||||
final bool loadingAddresses;
|
||||
final String? addressesError;
|
||||
final List<AddressRecord> addresses;
|
||||
final TextEditingController houseNumberController;
|
||||
final TextEditingController coloniaController;
|
||||
final TextEditingController streetController;
|
||||
final Future<void> Function() onSaveAddress;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: const Color(0xFFF8FAFC),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: ListView(
|
||||
children: [
|
||||
Card(
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Datos de la cuenta', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)),
|
||||
const SizedBox(height: 12),
|
||||
_ProfileRow(label: 'Nombre', value: session.displayName),
|
||||
_ProfileRow(label: 'Correo', value: session.email),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Card(
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Agregar otra dirección', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: houseNumberController,
|
||||
decoration: const InputDecoration(labelText: 'Número de casa', border: OutlineInputBorder()),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: coloniaController,
|
||||
decoration: const InputDecoration(labelText: 'Colonia', border: OutlineInputBorder()),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: streetController,
|
||||
decoration: const InputDecoration(labelText: 'Calle', border: OutlineInputBorder()),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: onSaveAddress,
|
||||
icon: const Icon(Icons.add_location_alt_outlined),
|
||||
label: const Text('Guardar nueva dirección'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Card(
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Direcciones registradas', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)),
|
||||
const SizedBox(height: 12),
|
||||
if (loadingAddresses) const Center(child: CircularProgressIndicator()),
|
||||
if (addressesError != null) Text(addressesError!, style: const TextStyle(color: Colors.red)),
|
||||
if (!loadingAddresses && addresses.isEmpty)
|
||||
const Text('Todavía no hay direcciones registradas.'),
|
||||
if (addresses.isNotEmpty)
|
||||
...addresses.map(
|
||||
(address) => Card(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.home_work_outlined, color: Colors.teal),
|
||||
title: Text('Casa ${address.houseNumber}'),
|
||||
subtitle: Text('${address.colonia}, ${address.street}'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProfileRow extends StatelessWidget {
|
||||
const _ProfileRow({required this.label, required this.value});
|
||||
|
||||
final String label;
|
||||
final String value;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(width: 90, child: Text(label, style: const TextStyle(fontWeight: FontWeight.w700))),
|
||||
Expanded(child: Text(value)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AppNotification {
|
||||
_AppNotification({required this.message, required this.timestamp});
|
||||
|
||||
final String message;
|
||||
final DateTime timestamp;
|
||||
}
|
||||
|
||||
class _NoticeBanner extends StatelessWidget {
|
||||
const _NoticeBanner({required this.message});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFE0F2FE),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFF7DD3FC)),
|
||||
),
|
||||
child: Text(message, style: const TextStyle(color: Color(0xFF075985))),
|
||||
);
|
||||
}
|
||||
}
|
||||
155
lib/screens/home_screen.dart
Normal file
155
lib/screens/home_screen.dart
Normal file
@@ -0,0 +1,155 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../models/address_entry.dart';
|
||||
import '../models/auth_session.dart';
|
||||
import '../services/auth_repository.dart';
|
||||
import '../services/address_repository.dart';
|
||||
import 'auth_screen.dart';
|
||||
|
||||
class HomeScreen extends StatelessWidget {
|
||||
const HomeScreen({
|
||||
super.key,
|
||||
required this.authRepository,
|
||||
required this.addressRepository,
|
||||
required this.session,
|
||||
this.savedAddress,
|
||||
});
|
||||
|
||||
final AuthRepository authRepository;
|
||||
final AddressRepository addressRepository;
|
||||
final AuthSession session;
|
||||
final AddressEntry? savedAddress;
|
||||
|
||||
Future<void> _logOut(BuildContext context) async {
|
||||
await authRepository.signOut();
|
||||
if (!context.mounted) {
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pushAndRemoveUntil(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => AuthScreen(
|
||||
authRepository: authRepository,
|
||||
addressRepository: addressRepository,
|
||||
),
|
||||
),
|
||||
(route) => false,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Container(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFFF8FAFC), Color(0xFFE2E8F0), Color(0xFFCCFBF1)],
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 520),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Card(
|
||||
elevation: 12,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 34,
|
||||
backgroundColor: const Color(0xFF0F766E).withValues(alpha: 0.12),
|
||||
child: Text(
|
||||
session.displayName.isNotEmpty ? session.displayName[0].toUpperCase() : 'U',
|
||||
style: const TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Color(0xFF0F766E),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Hola, ${session.displayName}',
|
||||
style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
session.email,
|
||||
style: TextStyle(color: Colors.grey.shade700),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_InfoTile(
|
||||
icon: Icons.dns_outlined,
|
||||
title: 'Dirección guardada',
|
||||
subtitle: savedAddress == null
|
||||
? 'Todavía no hay una dirección registrada para esta sesión.'
|
||||
: 'Casa ${savedAddress!.houseNumber}, Colonia ${savedAddress!.colonia}, Calle ${savedAddress!.street}',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_InfoTile(
|
||||
icon: Icons.storage_outlined,
|
||||
title: 'Persistencia en PostgreSQL',
|
||||
subtitle: 'La dirección se envió al backend con el token de sesión para almacenarla en la base de datos.',
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton.icon(
|
||||
onPressed: () => _logOut(context),
|
||||
icon: const Icon(Icons.logout),
|
||||
label: const Text('Cerrar sesión'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InfoTile extends StatelessWidget {
|
||||
const _InfoTile({required this.icon, required this.title, required this.subtitle});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFF8FAFC),
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
border: Border.all(color: const Color(0xFFE2E8F0)),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(icon, color: const Color(0xFF0F766E)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(title, style: const TextStyle(fontWeight: FontWeight.w700)),
|
||||
const SizedBox(height: 4),
|
||||
Text(subtitle, style: TextStyle(color: Colors.grey.shade700, height: 1.35)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
96
lib/services/address_repository.dart
Normal file
96
lib/services/address_repository.dart
Normal file
@@ -0,0 +1,96 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../app_config.dart';
|
||||
import '../models/address_entry.dart';
|
||||
import '../models/address_record.dart';
|
||||
import '../models/auth_session.dart';
|
||||
|
||||
abstract class AddressRepository {
|
||||
Future<void> saveAddress({
|
||||
required AuthSession session,
|
||||
required AddressEntry address,
|
||||
});
|
||||
|
||||
Future<List<AddressRecord>> getMyAddresses({required AuthSession session});
|
||||
}
|
||||
|
||||
class HttpAddressRepository implements AddressRepository {
|
||||
const HttpAddressRepository({http.Client? client}) : _client = client;
|
||||
|
||||
final http.Client? _client;
|
||||
|
||||
@override
|
||||
Future<void> saveAddress({
|
||||
required AuthSession session,
|
||||
required AddressEntry address,
|
||||
}) async {
|
||||
final uri = Uri.parse('${AppConfig.apiBaseUrl}/addresses');
|
||||
|
||||
late final http.Response response;
|
||||
try {
|
||||
response = await (_client ?? http.Client()).post(
|
||||
uri,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Authorization': 'Bearer ${session.token}',
|
||||
},
|
||||
body: jsonEncode(address.toJson()),
|
||||
);
|
||||
} catch (_) {
|
||||
throw AddressException(
|
||||
'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}.',
|
||||
);
|
||||
}
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
final payload = jsonDecode(response.body);
|
||||
final message = payload['message']?.toString() ?? 'Error al guardar la dirección.';
|
||||
throw AddressException(message);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<AddressRecord>> getMyAddresses({required AuthSession session}) async {
|
||||
final uri = Uri.parse('${AppConfig.apiBaseUrl}/addresses/me');
|
||||
|
||||
late final http.Response response;
|
||||
try {
|
||||
response = await (_client ?? http.Client()).get(
|
||||
uri,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': 'Bearer ${session.token}',
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
throw AddressException(
|
||||
'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}.',
|
||||
);
|
||||
}
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
final payload = jsonDecode(response.body);
|
||||
final message = payload['message']?.toString() ?? 'Error al obtener las direcciones.';
|
||||
throw AddressException(message);
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(response.body);
|
||||
if (decoded is! List) {
|
||||
return <AddressRecord>[];
|
||||
}
|
||||
|
||||
return decoded
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(AddressRecord.fromJson)
|
||||
.toList(growable: false);
|
||||
}
|
||||
}
|
||||
|
||||
class AddressException implements Exception {
|
||||
AddressException(this.message);
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
132
lib/services/auth_repository.dart
Normal file
132
lib/services/auth_repository.dart
Normal file
@@ -0,0 +1,132 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../app_config.dart';
|
||||
import '../models/auth_session.dart';
|
||||
|
||||
abstract class AuthRepository {
|
||||
Future<AuthSession?> restoreSession();
|
||||
Future<AuthSession> signIn({required String email, required String password});
|
||||
Future<AuthSession> signUp({required String name, required String email, required String password});
|
||||
Future<void> signOut();
|
||||
}
|
||||
|
||||
class HttpAuthRepository implements AuthRepository {
|
||||
const HttpAuthRepository({http.Client? client}) : _client = client;
|
||||
|
||||
final http.Client? _client;
|
||||
|
||||
static const String _tokenKey = 'auth_token';
|
||||
static const String _emailKey = 'auth_email';
|
||||
static const String _nameKey = 'auth_name';
|
||||
|
||||
@override
|
||||
Future<AuthSession?> restoreSession() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final token = prefs.getString(_tokenKey);
|
||||
final email = prefs.getString(_emailKey);
|
||||
final name = prefs.getString(_nameKey);
|
||||
|
||||
if (token == null || email == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return AuthSession(token: token, email: email, displayName: name ?? email);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<AuthSession> signIn({required String email, required String password}) {
|
||||
return _authenticate(
|
||||
endpoint: '/auth/login',
|
||||
body: <String, dynamic>{'email': email, 'password': password},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<AuthSession> signUp({required String name, required String email, required String password}) {
|
||||
return _authenticate(
|
||||
endpoint: '/auth/register',
|
||||
body: <String, dynamic>{'name': name, 'email': email, 'password': password},
|
||||
);
|
||||
}
|
||||
|
||||
Future<AuthSession> _authenticate({required String endpoint, required Map<String, dynamic> body}) async {
|
||||
final uri = Uri.parse('${AppConfig.apiBaseUrl}$endpoint');
|
||||
|
||||
late final http.Response response;
|
||||
try {
|
||||
response = await (_client ?? http.Client()).post(
|
||||
uri,
|
||||
headers: const <String, String>{
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: jsonEncode(body),
|
||||
);
|
||||
} catch (_) {
|
||||
throw AuthException(
|
||||
'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}. Verifica que el servicio esté activo.',
|
||||
);
|
||||
}
|
||||
|
||||
final Map<String, dynamic> payload = _decodeJson(response.body);
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
final message = payload['message']?.toString() ?? 'Credenciales inválidas o usuario no disponible.';
|
||||
throw AuthException(message);
|
||||
}
|
||||
|
||||
final token = payload['token']?.toString();
|
||||
if (token == null || token.isEmpty) {
|
||||
throw AuthException('El backend respondió sin token de sesión.');
|
||||
}
|
||||
|
||||
final user = payload['user'] is Map<String, dynamic>
|
||||
? payload['user'] as Map<String, dynamic>
|
||||
: <String, dynamic>{};
|
||||
final emailValue = (user['email'] ?? body['email'])?.toString() ?? body['email'].toString();
|
||||
final displayName = (user['name'] ?? user['fullName'] ?? body['name'] ?? emailValue).toString();
|
||||
|
||||
final session = AuthSession(token: token, email: emailValue, displayName: displayName);
|
||||
await _persistSession(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
Future<void> _persistSession(AuthSession session) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_tokenKey, session.token);
|
||||
await prefs.setString(_emailKey, session.email);
|
||||
await prefs.setString(_nameKey, session.displayName);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decodeJson(String responseBody) {
|
||||
if (responseBody.trim().isEmpty) {
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(responseBody);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
return decoded;
|
||||
}
|
||||
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> signOut() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_tokenKey);
|
||||
await prefs.remove(_emailKey);
|
||||
await prefs.remove(_nameKey);
|
||||
}
|
||||
}
|
||||
|
||||
class AuthException implements Exception {
|
||||
AuthException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
Reference in New Issue
Block a user