From 34f45a912fe30ad86540207e86c22a85d56dd5e2 Mon Sep 17 00:00:00 2001 From: Marcos Date: Wed, 20 May 2026 10:05:47 +0200 Subject: [PATCH] feat: Enhance error handling in note loading and moving operations with detailed logging --- lib/data/app_database.dart | 32 ++++++++++++++++++++++++++------ lib/screens/home_screen.dart | 17 ++++++++++++++--- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/lib/data/app_database.dart b/lib/data/app_database.dart index 40f7407..e386b23 100644 --- a/lib/data/app_database.dart +++ b/lib/data/app_database.dart @@ -133,21 +133,41 @@ class AppDatabase extends _$AppDatabase { } return transaction(() async { - if (oldIndex < newIndex) { + final List all = await (select(notes) + ..where((n) => n.isDeleted.equals(false))) + .get(); + + final int count = all.length; + if (count == 0) { + return; + } + + final int maxIndex = count - 1; + + final int safeOld = oldIndex.clamp(0, maxIndex); + final int safeNew = newIndex.clamp(0, maxIndex); + + if (safeOld == safeNew) { + return; + } + + if (safeOld < safeNew) { await customStatement( 'UPDATE notes SET sort_index = sort_index - 1 WHERE sort_index > ? AND sort_index <= ? AND is_deleted = 0', - [oldIndex, newIndex], + [safeOld, safeNew], ); } else { await customStatement( 'UPDATE notes SET sort_index = sort_index + 1 WHERE sort_index >= ? AND sort_index < ? AND is_deleted = 0', - [newIndex, oldIndex], + [safeNew, safeOld], ); } - await customStatement( - 'UPDATE notes SET sort_index = ?, updated_at = ? WHERE id = ?', - [newIndex, DateTime.now().toIso8601String(), id], + await (update(notes)..where((n) => n.id.equals(id))).write( + NotesCompanion( + sortIndex: Value(safeNew), + updatedAt: Value(DateTime.now()), + ), ); }); } diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index 72c60ba..f42589e 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -102,7 +102,9 @@ class _HomeScreenState extends State { _notes = storedNotes; _isLoading = false; }); - } catch (e) { + } catch (e, st) { + // Log the error so we can inspect the root cause before resetting the vault. + debugPrint('Failed to load notes: $e\n$st'); // If loading notes fails (e.g., DB corrupt), notify the app to reset the vault. if (widget.onVaultInvalid != null) { await widget.onVaultInvalid!(); @@ -145,8 +147,17 @@ class _HomeScreenState extends State { final Note movedNote = _notes[oldIndex]; - await widget.repository.moveNote(movedNote, newIndex); - await _loadNotes(); + try { + await widget.repository.moveNote(movedNote, newIndex); + await _loadNotes(); + } catch (e, st) { + // Don't let DB errors cause the app to reset the vault automatically. + debugPrint('Failed to move note: $e\n$st'); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error al reordenar la nota: $e')), + ); + } } Future _openNoteEditor(Note note) async {