I’ll introduce sample code for displaying images from assets in Flutter.
I implemented the functionality to display images from assets by referring to the following article from the official Flutter documentation:
The assets handled in this article will be limited to assets/images/codenote-net-200x200.jpg only.
$ tree assets
assets
└── images
└── codenote-net-200x200.jpg
1 directory, 1 file
Sample code for displaying images added to assets/ in Flutter app is published in the following GitHub Pull Request, so please take a look.
💡 Display the image from assets · Pull Request #12 · codenote-net/flutter_sandbox
If you encounter an error message like Unable to load asset: assets/images/xxx.jpg, check the assets definition in pubspec.yaml.
Incorrect assets definition
flutter:
assets:
- assets/
Correct assets definition
Note that only files located directly in the directory are included. To add files located in subdirectories, create an entry per directory.
As stated in the official documentation, defining just assets/ does not recursively specify files within directories directly under assets/.
Therefore, you need to explicitly define up to the directory where the image files are located, as follows:
flutter:
assets:
- assets/images/
Detailed Error Message
I/flutter ( 8558): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
I/flutter ( 8558): The following assertion was thrown resolving an image codec:
I/flutter ( 8558): Unable to load asset: assets/images/codenote-net-200x200.jpg
I/flutter ( 8558):
I/flutter ( 8558): When the exception was thrown, this was the stack:
I/flutter ( 8558): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
I/flutter ( 8558):
I/flutter ( 8558): #1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:484:44)
I/flutter ( 8558): #2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:469:14)
I/flutter ( 8558): #3 ImageProvider.resolve... (package:flutter/src/painting/image_provider.dart:327:17)
I/flutter ( 8558): #4 ImageCache.putIfAbsent (package:flutter/src/painting/image_cache.dart:160:22)
I/flutter ( 8558): #5 ImageProvider.resolve.. (package:flutter/src/painting/image_provider.dart:325:84)
I/flutter ( 8558): (elided 13 frames from package dart:async)
I/flutter ( 8558):
I/flutter ( 8558): Image provider: AssetImage(bundle: null, name: "assets/images/codenote-net-200x200.jpg")
I/flutter ( 8558): Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#5006d(), name:
I/flutter ( 8558): "assets/images/codenote-net-200x200.jpg", scale: 1.0)
I/flutter ( 8558): ════════════════════════════════════════════════════════════════════════════════════════════════════
That’s all about implementing functionality to display images from assets in Flutter from the Gemba.
That’s all from the Gemba.