Is there a way to check the database version in a flutter app using sqflite?

不打扰是莪最后的温柔 提交于 2020-05-08 05:37:09

问题


I am pretty new to flutter and I have some questions about how database version control works for these apps with sqflite.

I have made a database file in my assets folder that is copied onto the device of the user when the app is launched. I am wondering if there is any way to check the current version the user has of the database file, so that it does not have to be copied over every time?

Case: I make an update to the database file that is shipped with an app update in the google play store. Can the version of the database file that the user currently has, be checked to determine if a new file should replace the old one?

If so... Can I do this check every time I update my app? Do I have to do it every time the app is opened?

If not.. How is this best handled? What is the best way of handling database updates of files stored on a users device?


回答1:


SQFlite has already a built-in version management, but it will work only if you have a migration script. For what you've said that's probably not your case. You'll need to manage your version control by hand:

    class DbHelper {
      static const NEW_DB_VERSION = 2;

      static final DbHelper _instance = DbHelper.internal();

      factory DbHelper() => _instance;

      DbHelper.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, "database.db");

        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();

          //delete the old database so you can copy the new one
          await deleteDatabase(path);

          try {
            await Directory(dirname(path)).create(recursive: true);
          } catch (_) {}

          //copy db from assets to database folder
          ByteData data = await rootBundle.load("assets/databases/database.db");
          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;
      }
    }



来源:https://stackoverflow.com/questions/60458746/is-there-a-way-to-check-the-database-version-in-a-flutter-app-using-sqflite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!