feat: Implement force sync functionality in settings screen and update initial sync logic

This commit is contained in:
2026-05-18 21:04:59 +02:00
parent da0654cd4e
commit beadf860e2
2 changed files with 206 additions and 100 deletions
+4 -2
View File
@@ -202,8 +202,9 @@ class _NotesAppState extends State<NotesApp>
// Start periodic sync // Start periodic sync
_startPeriodicSync(); _startPeriodicSync();
// Run an initial full sync immediately to pull server changes // Run an initial sync immediately and let the repository use the
unawaited(_performSync(forceFull: true)); // stored lastSyncAt when it exists.
unawaited(_performSync());
} catch (e) { } catch (e) {
// If the database file is not a valid SQLite DB (e.g., wrong key or corruption), // If the database file is not a valid SQLite DB (e.g., wrong key or corruption),
// reset the local vault so the app doesn't crash. The reset will delete DB files // reset the local vault so the app doesn't crash. The reset will delete DB files
@@ -720,6 +721,7 @@ class _NotesAppState extends State<NotesApp>
key: const ValueKey<String>('settings-screen'), key: const ValueKey<String>('settings-screen'),
onDeleteAllData: _resetLocalVaultData, onDeleteAllData: _resetLocalVaultData,
onBackToHome: _openHome, onBackToHome: _openHome,
onForceSync: () => _performSync(forceFull: true),
); );
return MaterialApp( return MaterialApp(
+135 -31
View File
@@ -8,10 +8,12 @@ class SettingsScreen extends StatefulWidget {
super.key, super.key,
required this.onDeleteAllData, required this.onDeleteAllData,
required this.onBackToHome, required this.onBackToHome,
required this.onForceSync,
}); });
final Future<void> Function() onDeleteAllData; final Future<void> Function() onDeleteAllData;
final VoidCallback onBackToHome; final VoidCallback onBackToHome;
final Future<void> Function() onForceSync;
@override @override
State<SettingsScreen> createState() => _SettingsScreenState(); State<SettingsScreen> createState() => _SettingsScreenState();
@@ -19,6 +21,7 @@ class SettingsScreen extends StatefulWidget {
class _SettingsScreenState extends State<SettingsScreen> { class _SettingsScreenState extends State<SettingsScreen> {
bool _isBusy = false; bool _isBusy = false;
bool _isSyncing = false;
final TextEditingController _endpointController = TextEditingController(); final TextEditingController _endpointController = TextEditingController();
final TextEditingController _encryptionKeyController = TextEditingController(); final TextEditingController _encryptionKeyController = TextEditingController();
bool _endpointLoading = true; bool _endpointLoading = true;
@@ -30,7 +33,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Borrar todos los datos'), title: const Text('Borrar todos los datos'),
content: const Text('¿Estás seguro? Esta acción eliminará la base de datos local y la clave de cifrado. No se podrá recuperar.'), content: const Text('¿Estás seguro? Esta acción eliminará la base de datos local y la clave de cifrado. Asegúrate de tener una copia de seguridad si es necesario o cuenta sincronizada.'),
actions: [ actions: [
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancelar')), TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancelar')),
TextButton(onPressed: () => Navigator.of(context).pop(true), child: const Text('Borrar', style: TextStyle(color: Colors.red))), TextButton(onPressed: () => Navigator.of(context).pop(true), child: const Text('Borrar', style: TextStyle(color: Colors.red))),
@@ -65,6 +68,38 @@ class _SettingsScreenState extends State<SettingsScreen> {
} }
} }
Future<void> _forceSync() async {
if (_isBusy || _isSyncing) {
return;
}
setState(() {
_isSyncing = true;
});
try {
await widget.onForceSync();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Sincronización forzada completada.')),
);
} catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error al forzar la sincronización: $error')),
);
} finally {
if (!mounted) return;
setState(() {
_isSyncing = false;
});
}
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -151,6 +186,56 @@ class _SettingsScreenState extends State<SettingsScreen> {
_endpointController.text = endpoint; _endpointController.text = endpoint;
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Endpoint restaurado al valor por defecto'))); ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Endpoint restaurado al valor por defecto')));
} }
Widget _buildResponsiveInputActionsRow({
required Widget input,
required List<Widget> actions,
}) {
return LayoutBuilder(
builder: (context, constraints) {
final bool isCompact = constraints.maxWidth < 600;
if (isCompact) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(width: double.infinity, child: input),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: Wrap(
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 8,
children: actions,
),
),
],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: input),
const SizedBox(width: 8),
Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (int index = 0; index < actions.length; index++) ...[
if (index > 0) const SizedBox(width: 8),
actions[index],
],
],
),
),
],
);
},
);
}
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
body: Container( body: Container(
@@ -181,22 +266,58 @@ class _SettingsScreenState extends State<SettingsScreen> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row(
children: [
const Expanded(
child: Text('Borrar datos locales:'),
),
ElevatedButton.icon( ElevatedButton.icon(
style: ElevatedButton.styleFrom(backgroundColor: Colors.redAccent), style: ElevatedButton.styleFrom(
backgroundColor: Colors.redAccent,
foregroundColor: Colors.white,
textStyle: const TextStyle(fontWeight: FontWeight.w600),
),
onPressed: _isBusy ? null : _confirmAndDeleteAll, onPressed: _isBusy ? null : _confirmAndDeleteAll,
icon: _isBusy ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) : const Icon(Icons.delete_forever), icon: _isBusy
label: const Text('Borrar todos los datos'), ? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.delete_forever),
label: const Text('Borrar'),
),
],
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
const Text('Esto cerrará el vault actual y eliminará la base de datos local junto con la clave de cifrado.'), Row(
children: [
const Expanded(
child: Text('Forzar sincronizacion total:'),
),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.amber,
foregroundColor: Colors.black,
textStyle: const TextStyle(fontWeight: FontWeight.w700),
),
onPressed: (_isBusy || _isSyncing) ? null : _forceSync,
icon: _isSyncing
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.sync),
label: const Text('Sincronizar'),
),
],
),
const SizedBox(height: 24), const SizedBox(height: 24),
const Text('API endpoint (ej: http://localhost:3000/api)'), const Text('API endpoint (ej: http://localhost:3000/api)'),
const SizedBox(height: 8), const SizedBox(height: 8),
Row( _buildResponsiveInputActionsRow(
crossAxisAlignment: CrossAxisAlignment.start, input: _endpointLoading
children: [
Expanded(
child: _endpointLoading
? const SizedBox(height: 48, child: Center(child: CircularProgressIndicator())) ? const SizedBox(height: 48, child: Center(child: CircularProgressIndicator()))
: TextField( : TextField(
controller: _endpointController, controller: _endpointController,
@@ -221,32 +342,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
), ),
), ),
), ),
), actions: [
const SizedBox(width: 8),
Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton( ElevatedButton(
onPressed: _endpointLoading ? null : _saveEndpoint, onPressed: _endpointLoading ? null : _saveEndpoint,
child: const Text('Guardar'), child: const Text('Guardar'),
), ),
const SizedBox(height: 8),
OutlinedButton( OutlinedButton(
onPressed: _endpointLoading ? null : _resetEndpoint, onPressed: _endpointLoading ? null : _resetEndpoint,
child: const Text('Restaurar'), child: const Text('Restaurar'),
), ),
], ],
), ),
],
),
const SizedBox(height: 24), const SizedBox(height: 24),
const Text('Clave de cifrado local'), const Text('Clave de cifrado local'),
const SizedBox(height: 8), const SizedBox(height: 8),
Row( _buildResponsiveInputActionsRow(
crossAxisAlignment: CrossAxisAlignment.start, input: TextField(
children: [
Expanded(
child: TextField(
controller: _encryptionKeyController, controller: _encryptionKeyController,
readOnly: true, readOnly: true,
obscureText: !_encryptionKeyVisible, obscureText: !_encryptionKeyVisible,
@@ -272,11 +383,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
), ),
), ),
), ),
), actions: [
const SizedBox(width: 8),
Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton( ElevatedButton(
onPressed: _encryptionKeyLoading ? null : _loadEncryptionKey, onPressed: _encryptionKeyLoading ? null : _loadEncryptionKey,
child: _encryptionKeyLoading child: _encryptionKeyLoading
@@ -287,7 +394,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
) )
: const Text('Mostrar'), : const Text('Mostrar'),
), ),
const SizedBox(height: 8),
OutlinedButton( OutlinedButton(
onPressed: _encryptionKeyVisible ? _hideEncryptionKey : null, onPressed: _encryptionKeyVisible ? _hideEncryptionKey : null,
child: const Text('Ocultar'), child: const Text('Ocultar'),
@@ -296,8 +402,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
), ),
], ],
), ),
],
),
), ),
), ),
], ],