notes/lib/savesystem/note_file.dart

88 lines
2.1 KiB
Dart
Raw Normal View History

import 'dart:io';
2022-11-03 10:22:38 +00:00
import 'package:flutter/widgets.dart';
2022-10-29 18:06:20 +00:00
import 'package:sqflite/sqflite.dart';
import 'path.dart';
2022-10-29 18:06:20 +00:00
class NoteFile {
2022-11-17 10:39:06 +00:00
Database? _db;
String filename;
2022-11-17 10:39:06 +00:00
String? _basePath;
String? _newFileName;
2022-10-29 18:06:20 +00:00
Database db() {
2022-11-17 10:39:06 +00:00
assert(_db != null);
return _db!;
2022-10-29 18:06:20 +00:00
}
NoteFile(this.filename);
2022-10-29 18:06:20 +00:00
Future<void> init() async {
2022-11-17 10:39:06 +00:00
if (_basePath == null) {
await _initBasePath();
}
final path = _basePath! + Platform.pathSeparator + filename;
2022-10-29 18:06:20 +00:00
_db = await openDatabase(
path,
onCreate: (db, version) async {
2022-11-03 10:22:38 +00:00
final batch = db.batch();
batch.execute('DROP TABLE IF EXISTS strokes;');
batch.execute('DROP TABLE IF EXISTS points;');
batch.execute(
'CREATE TABLE strokes(id integer primary key autoincrement, color INTEGER, elevation INTEGER)');
batch.execute(
'CREATE TABLE points(id integer primary key autoincrement, x INTEGER, y INTEGER, thickness REAL, strokeid INTEGER)');
await batch.commit();
return;
2022-10-29 18:06:20 +00:00
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
}
Future<void> delete() async {
await close();
2022-11-17 10:39:06 +00:00
if (_basePath == null) {
await _initBasePath();
}
await File(_basePath! + Platform.pathSeparator + filename).delete();
}
void rename(String newname) {
_newFileName = newname;
2022-10-29 18:06:20 +00:00
}
Future<void> close() async {
// shrink the db file size
2022-11-17 10:39:06 +00:00
if (_db != null && _db!.isOpen) {
await _db!.execute('VACUUM');
await _db!.close();
2022-11-03 10:22:38 +00:00
} else {
debugPrint('db file unexpectedly closed before shrinking');
}
2022-11-17 10:39:06 +00:00
if (_basePath == null) {
await _initBasePath();
}
// perform qued file renaming operations
if (_newFileName != null) {
2022-11-17 10:39:06 +00:00
File(_basePath! + Platform.pathSeparator + filename)
.rename(_basePath! + Platform.pathSeparator + _newFileName!);
filename = _newFileName!;
_newFileName = null;
}
2022-10-29 18:06:20 +00:00
}
2022-11-17 10:39:06 +00:00
Future<void> _initBasePath() async {
_basePath = (await getSavePath()).path;
}
2022-10-29 18:06:20 +00:00
}