こんにちは。ざわかける!のざわ(@zw_kakeru)です。
Flutterで画像を追加しようとした時につまずいたので、そのTipsとなっています。
動作環境
macOS: 11.2.2 (Big Sur) Flutter: 2.0.1 Dart: 2.12.0 Visual Studio Code: 1.53.2
やったこととエラーの内容
自作アプリ内に画像を挿入しようと思い、assetsディレクトリにhoge.pngを置いて、実行。
すると、以下のエラーが出ました。
══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: assets/hoge.png
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:227:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:667:14)
<asynchronous suspension>
...
Image provider: AssetImage(bundle: null, name: "assets/hoge.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#ce30c(), name:
"assets/hoge.png", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════
Another exception was thrown: Unable to load asset: assets/hoge.png
解決策
pubspec.yaml内のassetsの記述がflutterインデントブロックに入っていませんでした。
assets:
- assets/
これをflutterインデントブロックに入れてあげます。
flutter:
assets:
- assets/
保存して再度実行すると、エラーが消えて無事に画像が出力されました。
終わりに
インデントミスという初歩的すぎて検索しても全然出てこないミスでした。
pubspec.yamlがインデントを気にする必要があるということは知っていたのですが、dartのパッケージ記法の理解が足りておらず、解決に少し手間取りました。
これくらいの軽すぎるTipsは記事として上げるかどうか迷いますね。
その日のコンディションに左右される部分かもしれません。