Невозможно прочитать файл sql из активов в флаттере - PullRequest
0 голосов
/ 04 июня 2019

Я пытаюсь загрузить предварительно заполненные данные в мое приложение.Я создал папку «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));

1 Ответ

1 голос
/ 04 июня 2019

В моем коде было 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:

  # 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

Обратите внимание на отступ (2 пробела перед 'assets:')

2. файл sql не db Итак, я получил эту проблему после решения первого. Я получил mydb.sql не является базой данных. Поэтому я экспортировал свою базу данных в виде файла .sqlite из Sqlite Database Browser. & обновил мой файл pubspec & DBHandler.

Спасибо @ Shababb Karim за комментарий за указание на проблему pubspec.yaml.

...