Created
July 14, 2020 05:50
-
-
Save paulocoutinhox/ae5928a20457ba655b59109e7d721dcc to your computer and use it in GitHub Desktop.
Create a fresh or not database with Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Future<Database> loadDatabase() async { | |
bool alwaysFreshDatabase = true; | |
if (alwaysFreshDatabase) { | |
var databasesPath = await getDatabasesPath(); | |
var path = join(databasesPath, 'bible.db'); | |
// delete existing if any | |
await deleteDatabase(path); | |
// Make sure the parent directory exists | |
try { | |
await Directory(dirname(path)).create(recursive: true); | |
} catch (_) { | |
// ignore | |
} | |
// Copy from asset | |
ByteData data = await rootBundle.load(join('assets', 'db', 'bible.db')); | |
List<int> bytes = | |
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); | |
await new File(path).writeAsBytes(bytes, flush: true); | |
// open the database | |
return await openDatabase(path, readOnly: true); | |
} else { | |
var databasesPath = await getDatabasesPath(); | |
var path = join(databasesPath, 'bible.db'); | |
// Check if the database exists | |
var exists = await databaseExists(path); | |
if (!exists) { | |
// Should happen only the first time you launch your application | |
print('Creating new copy from asset'); | |
// Make sure the parent directory exists | |
try { | |
await Directory(dirname(path)).create(recursive: true); | |
} catch (_) { | |
// ignore | |
} | |
// Copy from asset | |
ByteData data = await rootBundle.load(join('assets', 'db', 'bible.db')); | |
List<int> bytes = | |
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); | |
// Write and flush the bytes written | |
await File(path).writeAsBytes(bytes, flush: true); | |
} else { | |
print('Opening existing database'); | |
} | |
// open the database | |
return await openDatabase(path, readOnly: true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment