📁
[Flutter] Unable to load asset エラーが出たときの確認事項
前提
-
以下のディレクトリにあるJSONファイルをプログラム内で読み込みたい。
data/category/sub_category/items.json
-
プログラム実行中に
Unable to load asset
エラーが出た。
-
pubspec.yaml
のインデントは正しく記述されている。 -
flutter clean
やアプリのコールドリスタート、再インストール等を試してみた。
原因
pubspec.yaml
でディレクトリ指定の書き方が違いました。
OK
flutter:
assets:
- data/category/sub_category/
NG
flutter:
assets:
- data/
読み込みたいファイルが直接属するディレクトリまでちゃんと指定しないといけないようです。
よく見たら公式ドキュメントに書いてありました。
Note: Only files located directly in the directory are included unless there are files with the same name inside a subdirectory (see Asset Variants). To add files located in subdirectories, create an entry per directory.
注:サブディレクトリ内に同じ名前のファイルがない限り、ディレクトリ内に直接あるファイルのみが含まれます(「アセットバリアント」を参照)。サブディレクトリにあるファイルを追加するには、ディレクトリごとにエントリを作成します。
Discussion