Flutter sqflite 打开现有数据库

dav*_*vid 10 database sqlite flutter

如何使用 flutter 和 sqflite 从资产中打开现有数据库?我阅读了本指南:https : //github.com/tekartik/sqflite/blob/master/doc/opening_db.md#preloading-data

但我的应用程序显示“未找到表”错误谢谢。

Art*_*ken 13

开口的资产数据库指南介绍你所要做的捆绑,并打开您的颤振应用内预先存在的SQLite数据库的步骤进行:

首先,您必须编辑您的pubspec.yaml配置以引用您预先存在的 SQLite 数据库文件,以便在构建应用程序时将其捆绑到您的应用程序中。在以下示例中,我们假设该文件存在于assets/demo.db您的 Flutter 应用程序目录下:

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/demo.db
Run Code Online (Sandbox Code Playgroud)

接下来,在您的应用程序初始化中,您需要将捆绑文件数据复制到可用位置,因为捆绑资源本身无法在 Android 上作为文件直接打开。

sqflite.getDatabasesPath()函数将返回用于此目的的目录。这通常与/data/data/org.example.myapp/databases/Android类似。有了这个,您可以从捆绑资产中加载字节数据并创建应用程序的可写数据库文件,此处命名为app.db

// Construct the path to the app's writable database file:
var dbDir = await getDatabasesPath();
var dbPath = join(dbDir, "app.db");

// Delete any existing database:
await deleteDatabase(dbPath);

// Create the writable database file from the bundled demo database file:
ByteData data = await rootBundle.load("assets/demo.db");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
Run Code Online (Sandbox Code Playgroud)

最后,您可以在应用程序启动时打开创建的数据库文件:

var db = await openDatabase(dbPath);
Run Code Online (Sandbox Code Playgroud)

  • @carlfrank 看起来他们重组了。这是更新的链接:https://github.com/tekartik/sqflite/blob/master/sqflite/doc/opening_asset_db.md (4认同)