flutter sqflite database resets when app is closed and reopened

Viewed 19

I'm working on my database to persist notes when the app is closed (process killed). It worked before the null-safety implementation, however, now it deletes all the data when I close the app and reopen it.

Here is the code of my Database class:

import 'dart:io';
import 'package:notaria/database/note.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class NotesDatabase {
  static final _dbName = 'notes.db';
  static final _dbVersion = 1;

  NotesDatabase._privateConstructor();
  static final NotesDatabase instance = NotesDatabase._privateConstructor();

  static Database? _database;

  Future<Database> get database async {
    if (_database != null) {
      return _database!;
    }
    return _database = await _initDatabase();
  }

  Future<Database> _initDatabase() async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = join(directory.path, _dbName);
    print(path);
    return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
  }

  Future<void> _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE notes (
            id TEXT,
            title TEXT,
            notetext TEXT,
            videourl TEXT,
            thumbnail TEXT
          )
          ''');
  }

  Future<List<Note>> getNotes() async {
    Database db = await instance.database;

    var notes = await db.query('notes');

    List<Note> noteList = notes.isNotEmpty
        ? notes.map((note) => Note.fromMap(note)).toList()
        : [];
    return noteList;
  }

  Future<int> insert(Note note) async {
    Database db = await instance.database;
    return await db.insert('notes', note.toMap());
  }

  Future<int> delete(int id) async {
    Database db = await instance.database;
    return await db.delete('notes', where: 'id = ?', whereArgs: [id]);
  }

  Future<int> update(Note note) async {
    Database db = await instance.database;
    return await db
        .update('notes', note.toMap(), where: 'id = ?', whereArgs: [note.id]);
  }
}

Is it possible that the database does not get opened properly? Or I overwrite the already existing database with empty text?

I'm thankful for any help.

0 Answers
Related