无法从 flutter 中的资产中读取 sql 文件

Unable to read sql file from assets in flutter

我正在尝试将预填充的数据加载到我的 flutter 应用程序中。 我在项目的根目录中创建了 'assets' 文件夹,并将 'mydb.sql' 文件放入该文件夹。

在 pubspec.yaml

中添加了该文件引用
assets:
  - assets/mydb.sql

下面是我的 DBHandler.dart 文件访问数据库的代码

  static Database _db;
  String dbName = "mydb.sql";

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

  initDb() async {
    var databasesPath = await getDatabasesPath();
    var path = join(databasesPath, dbName);
    var exists = await databaseExists(path);
    if (!exists) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");

      // Make sure the parent directory exists
      try {
        await io.Directory(dirname(path)).create(recursive: true);
      } catch (_) {}

      // Copy from asset
      ByteData data = await rootBundle.load(join('assets',dbName));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      // Write and flush the bytes written
      await io.File(path).writeAsBytes(bytes, flush: true);
    } else {
      print("Opening existing database");
    }
    return await openDatabase(path);
  }

我得到的错误是

I/flutter (16900): Creating new copy from asset
E/flutter (16900): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Unable to load asset: assets/mydb.sql
E/flutter (16900): #0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
E/flutter (16900): <asynchronous suspension>
E/flutter (16900): #1      DBHandler.initDb (package:MyApp/db/DBHandler.dart:36:40)

在代码的给定行下方。

ByteData data = await rootBundle.load(join('assets',dbName));

我的代码中有 2 个问题。写这篇文章是为了帮助其他人犯同样的错误。

1. pubspec.yaml
中的缩进 我犯了一个重大的愚蠢错误。我只是在看

assets:
  - assets/mydb.sql

我的 pubspec 文件是这样的

  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/mydb.sqlite

我没有注意到我的 'flutter:' 和 'assets:' 处于同一水平。 所以我将其更改为

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/mydb.sqlite

Notice the indentation (2 spaces before 'assets:')

2。 sql 文件不是 db 所以,我在解决第一个问题后遇到了这个问题。我得到 mydb.sql 不是数据库。所以我从 Sqlite 数据库浏览器将我的数据库导出为 '.sqlite' 文件。并更新了我的 pubspec 和 DBHandler 文件。

感谢 指出 pubspec.yaml 问题。