user2872856
user2872856

Reputation: 2051

Flutter sqflite - Replace database copied from asset onUpgrade

I have a local sqlite database saved in asset, which when the app open, it will be copied. When there is a new version of the database, the old file should be replaced. So what I do is simply copy the file again. This method has no issue on simulator and I successfully updated the database. However, in real device, the database failed to be copied.

I am using the following code to initialized the database

initDb() async {
    // Construct a file path to copy database to
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, 'dictionary');

    // Only copy if the database doesn't exist
    if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound) {
      // Load database from asset and copy
      ByteData data = await rootBundle.load(join('assets', 'dictionary'));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      // Save copied asset to documents
      await new File(path).writeAsBytes(bytes);
    }

    var theDb = await openDatabase(path, version: 4, onUpgrade: _onUpgrade);
    return theDb;
  }

This is my onUpgrade

void _onUpgrade(Database db, int oldVersion, int newVersion) async {
    var batch = db.batch();
    if (oldVersion < newVersion) {
      Directory documentsDirectory = await getApplicationDocumentsDirectory();
      String path = join(documentsDirectory.path, "dictionary");
      ByteData data = await rootBundle.load(join('assets', 'dictionary'));
      List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      // Save copied asset to documents
      await new File(path).writeAsBytes(bytes);
    }
    await batch.commit();
  }

What went wrong?

Upvotes: 3

Views: 1673

Answers (2)

user2872856
user2872856

Reputation: 2051

Found out the issue is nothing related to database. It is because of this StoreReview await method which I called before the database is loaded.

Future<void> _reviewApp() async {
    if (await StoreReview.isAvailable) {
      StoreReview.requestReview();
    }
  }

The await is blocking loading of my database. Fixed the issue by changing to .then

_reviewApp() {
    StoreReview.isAvailable.then((onValue) {
      if(onValue) {
        StoreReview.requestReview();
      }
    });
  }

Upvotes: 0

FloW
FloW

Reputation: 1266

i think you can not replace the db file when you open it at the same time at onUpgrade:

here is an example how it works Is there a way to check the database version in a flutter app using sqflite?

Upvotes: 1

Related Questions