import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; import '../models/note.dart'; import 'note_repository.dart'; class LocalNoteRepository implements NoteRepository { static Database? _db; Future get _database async { _db ??= await _initDb(); return _db!; } Future _initDb() async { final dbPath = await getDatabasesPath(); final path = join(dbPath, 'notes.db'); return openDatabase( path, version: 1, onCreate: (db, version) => db.execute(''' CREATE TABLE notes ( id TEXT PRIMARY KEY, title TEXT NOT NULL, content TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ) '''), ); } @override Future> getAll() async { final db = await _database; final rows = await db.query('notes', orderBy: 'updated_at DESC'); return rows.map(Note.fromMap).toList(); } @override Future getById(String id) async { final db = await _database; final rows = await db.query('notes', where: 'id = ?', whereArgs: [id]); if (rows.isEmpty) return null; return Note.fromMap(rows.first); } @override Future save(Note note) async { final db = await _database; await db.insert( 'notes', note.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); return note; } @override Future delete(String id) async { final db = await _database; await db.delete('notes', where: 'id = ?', whereArgs: [id]); } }