📲

【Flutter】flutter_gen で、画像のPathを取得したい

に公開

🗒️ 概要

fluter_genを更新後、追加した画像で「.path」アクセスができなかった。

// 🚨エラー(新規追加した画像)
print(Assets.images.mobile.icon.newImage.path);

// 👌OK(すでに追加済みの画像)
print(Assets.images.mobile.icon.oldImage.path);

※新規画像追加後に、コード生成コマンド実行後
$ dart run build_runner build --delete-conflicting-outputs

💡 対応

  • pubspec.yamlの末尾あたりに、
  • [flutter_gen:]の設定項目を追加し
  • 「.path」の有効化を設定
// pubspec.yaml

...

# flutter_gen の各種設定を追記
# 生成コマンド-> dart run build_runner build --delete-conflicting-outputs 
flutter_gen:
  assets:
    outputs:
      directory_path_enabled: true # <- 💡これで、「.path」アクセスを有効化

として、コード生成コマンド実行後、確認してOK👍
$ dart run build_runner build --delete-conflicting-outputs

👌動作確認

// 👌(新規追加した画像)
print(Assets.images.mobile.icon.newImage.path); // -> "assets/images/mobile.icon.new_image.png"

Discussion