📁

[Flutter] Unable to load asset エラーが出たときの確認事項

2022/11/19に公開

前提

  1. 以下のディレクトリにあるJSONファイルをプログラム内で読み込みたい。
    data/category/sub_category/items.json

  2. プログラム実行中に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