I am using the following code to copy database from asset. Most of time time, this code work fine. However, after my app was published to app store, I received complain from some users whereby the database failed to load. Then I tried on my own iPhone, uninstall and download the app again from app store. The weird thing is out of approximately 10 times installation, there is 1 time the database failed to load. This is my database helper:
class DatabaseHelper {
static const NEW_DB_VERSION = 6;
static final DatabaseHelper _instance = DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
DatabaseHelper.internal();
Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
} else {
_db = await initDb();
return _db;
}
}
Future<Database> initDb() async {
final databasesPath = await getDatabasesPath();
final path = join(databasesPath, "dictionary");
var db = await openDatabase(path);
//if database does not exist yet it will return version 0
if (await db.getVersion() < NEW_DB_VERSION) {
db.close();
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
//copy db from assets to database folder
ByteData data = await rootBundle.load("assets/dictionary");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(path).writeAsBytes(bytes, flush: true);
//open the newly created db
db = await openDatabase(path);
//set the new version to the copied db so you do not need to do it manually on your bundled database.db
db.setVersion(NEW_DB_VERSION);
}
return db;
}
}
I initialize the database in my main activity by using
DatabaseHelper db = DatabaseHelper();
Why this weird problem happened?