Flutter sqflite-替换从资产onUpgrade复制的数据库

时间:2020-04-28 09:12:29

标签: flutter sqflite

我在资产中保存了一个本地sqlite数据库,当应用打开时,它将被复制。当有新版本的数据库时,应替换旧文件。因此,我要做的只是简单地再次复制文件。此方法在模拟器上没有问题,我已成功更新了数据库。但是,在实际设备中,数据库无法复制。

我正在使用以下代码初始化数据库

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;
  }

这是我的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();
  }

出了什么问题?

2 个答案:

答案 0 :(得分:1)

我认为您无法同时在onUpgrade:中打开db文件

这是一个示例,它如何工作 Is there a way to check the database version in a flutter app using sqflite?

答案 1 :(得分:0)

发现问题与数据库无关。因为在加载数据库之前调用了此StoreReview await方法。

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

await正在阻止加载我的数据库。通过更改为.then

解决了该问题
_reviewApp() {
    StoreReview.isAvailable.then((onValue) {
      if(onValue) {
        StoreReview.requestReview();
      }
    });
  }