【问题标题】:Deleting database with sqlflite in flutter doesn't seem to be working在颤振中使用 sqlflite 删除数据库似乎不起作用
【发布时间】:2019-06-18 10:57:26
【问题描述】:

对于我的应用程序,我正在为遵循本教程的用户加载预填充的数据库,其中包含一些初始/默认数据:https://github.com/tekartik/sqflite/blob/master/doc/opening_asset_db.md 在调试时,我将添加/删除一堆测试数据,并且不想每次我想重新加载应用程序时都必须手动重置,所以我让它每次都从数据库中加载一个新副本。

但由于某种原因,它并没有从资产加载新副本,而是仍然打开现有的修改数据库。我检查了资产文件,它没有被修改,并且没有达到在机器上打开现有数据库而不删除以前版本的块。

我在控制台中也没有收到任何错误。

这是初始化数据库的代码:

static Database _db;

  Future<Database> get db async {
    if(_db != null)
      return _db;
    _db = await initDb();
    return _db;
  }

  bool get isInDebugMode {
    bool inDebugMode = false;
    assert(inDebugMode = true);
    return inDebugMode;
  }

  //load database from existing db or copy pre-loaded db from assets
  initDb() async {
    //if in debug mode always load from asset file
    //done to reload from asset when default values added to database asset
    //and get rid of testing data
    //since it would be annoying to have to delete the file on the emulator every time

    debugPrint("initializing the db connection");
    var databasesPath = await getDatabasesPath();
    var path = join(databasesPath, "myDatabase.db");

    if(isInDebugMode){
      // delete existing if any
      await deleteDatabase(path);

      // Copy from asset
      ByteData data = await rootBundle.load(join("assets", "assetDB.db"));
      List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      await new File(path).writeAsBytes(bytes);

      // open the database
      var db = await openDatabase(path, readOnly: false);
      return db;

    } else {
      // try opening (will work if it exists)
      Database db;
      try {
        db = await openDatabase(path, readOnly: false);
      } catch (e) {
        print("Error $e");
      }

      if (db == null) {
        // Should happen only the first time you launch your application
        print("Creating new copy from asset");

        // Copy from asset
        ByteData data = await rootBundle.load(join("assets", "assetDB.db"));
        List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
        await new File(path).writeAsBytes(bytes);

        //debugPrint(bytes.length.toString());

        // open the database
        db = await openDatabase(path, readOnly: true);
      } else {
        print("Opening existing database");
      }

      return db;
    }

  }

我应该提到,当我加载这些更改时,我并没有进行热重载,并且到达了在调试模式下从资产初始化新数据库的块。

感谢您的帮助!

【问题讨论】:

    标签: sqlite dart flutter


    【解决方案1】:

    除非您格外小心,否则 Hotreload 和插件并不总是能很好地配合使用。在您的情况下,您尝试删除可能仍处于打开状态的数据库。所以你应该在删除它之前尝试关闭它。一种解决方案是在调用 deleteDatabase 之前保存对数据库的全局引用并关闭它

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      相关资源
      最近更新 更多