簡體   English   中英

無法從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數據=等待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

注意縮進(“ assets:”之前的2個空格)

2. sql文件不是db,所以在解決第一個問題后出現了這個問題。 我得到了mydb.sql不是數據庫。 因此,我從Sqlite數據庫瀏覽器將數據庫導出為“ .sqlite”文件。 並更新了我的pubspec和DBHandler文件。

感謝@Shababb Karim的評論指出了pubspec.yaml問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM