【问题标题】:Flutter sqflite - Replace database copied from asset onUpgradeFlutter sqflite - 替换从资产 onUpgrade 复制的数据库
【发布时间】:2020-04-28 09:12:29
【问题描述】:

我有一个本地 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();
  }

出了什么问题?

【问题讨论】:

    标签: flutter sqflite


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      await 阻止加载我的数据库。通过更改为.then修复了该问题

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-14
        • 2021-06-22
        • 2012-07-08
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多