Skip to content

Instantly share code, notes, and snippets.

@henry2man
Last active August 31, 2021 14:24
Show Gist options
  • Save henry2man/bb491b0146cf0258879e96743169cccd to your computer and use it in GitHub Desktop.
Save henry2man/bb491b0146cf0258879e96743169cccd to your computer and use it in GitHub Desktop.
Flutter PersistenceController with initialization from Assets Backup and restore capabilities. Uses Floor. This is handmade, I've removed some stuff... in order to use it in your code you'll need to adapt it. My code is able to: Preload the database file with a copy that is stored in app assets. Create a backup in the SD Card Restore the databas…
import 'dart:async';
import 'dart:io';
import 'package:floor/floor.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
part 'persistence_controller.g.dart'; // the generated code will be there
@Database(version: 1, entities: [Entity])
abstract class AppDatabase extends FloorDatabase {
EntityDao get entityDao;
}
class PersistenceController {
static const _databaseFile = 'app_database.db';
static AppDatabase _database;
static Future<void> init() async {
final callback = Callback(
onCreate: (database, version) {
/* database has been created */
},
onOpen: (database) {
/* database has been opened */
},
onUpgrade: (database, startVersion, endVersion) {
/* database has been upgraded */
},
);
// Copy database from assets folder
await initializeDatabase(_databaseFile);
_database = await $FloorAppDatabase
.databaseBuilder(_databaseFile)
.addCallback(callback)
.build();
}
static Future<void> shutdown() {
return _database.close();
}
static Future<void> createBackup(String database) {
return _backup(database, true, state);
}
static Future<void> restoreBackup(String database) {
return _backup(database, false, state);
}
static Future<void> _backup(
final String database, bool export) async {
// Shutdown database
await shutdown();
var internalPath = join(await sqflite.getDatabasesPath(), database);
var externalPath = join(await getExternalStorageDirectory().path, database);
if (export) {
copyFile(
sourcePath: internalPath, destinationPath: externalPath);
} else {
copyFile(
sourcePath: externalPath, destinationPath: internalPath);
}
// Init database
await init(state);
}
static void copyFile({String sourcePath, String destinationPath}) {
File(destinationPath).create(recursive: true);
File(sourcePath).copySync(destinationPath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment