Flutter Desktop 读取本地assets目录下的数据库(.db)文件

一、添加第三方库

flutter pub add sqflite_common_ffi

二、在pubspec.yaml中配置assets

注意格式

assets:
  - assets/xxx.db

三、初始化数据库
项目初始化以后会从根目录下的.dart_tool/sqflite_common_ffi/databases/xxx.db读取数据库文件,如果没有则把assets目录下的拷贝到该目录下。

  initialDatabase() async {
    sqfliteFfiInit();
    var databaseFactory = databaseFactoryFfi;
    var databasesPath = await databaseFactory.getDatabasesPath();

    var path = join(databasesPath, "express.db");

    print(path);
    var exists = await databaseFactory.databaseExists(path);

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

      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (_) {}
      // Copy from asset
      ByteData data = await rootBundle.load('assets/express.db');
      print(join('assets','express.db'));
      // ByteData data = await rootBundle.load(join('assets','express.db'));
      List bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      // Write and flush the bytes written
      await File(path).writeAsBytes(bytes, flush: true);
    } else {
      print("Opening existing database");
    }
    // open the database
    this._db = await databaseFactory.openDatabase(path);
    print(databasesPath);
  }

四、查询数据

  // 查询
  Future> queryPrice() async {
    List priceList = [];
    var result = await _db.query(table_name, where: 'id = ?', whereArgs: [1]);
    return priceList;
  }

你可能感兴趣的:(Flutter Desktop 读取本地assets目录下的数据库(.db)文件)