Reputation: 13434
This is the folder structure of my app
.idea
.vscode
android
build
fonts
Oxygen-Bold.tff
Oxygen-Light.tff
Oxygen-Regular.tff
images
pizza0.png
pizza1.png
ios
lib
ui
home.dart
main.dart
test
.gitignore
.metadata
.packages
app_widgets.iml
pubspec.lock
pubspec.yaml
README.md
In my pubspec.yaml
file, I load the fonts and assets like this
flutter:
uses-material-design: true
assets:
- images/pizza0.png
- images/pizza1.png
fonts:
- family: Oxygen
fonts:
- asset: fonts/Oxygen-Regular.ttf
- asset: fonts/Oxygen-Bold.ttf
weight: 700
- asset: fonts/Oxygen-Light.ttf
weight: 300
I'm not getting any errors for this pubspec.yaml
, and running flutter packages get
gives an exit code of 0.
In my home.dart I have the following class:
class PizzaImageWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
AssetImage pizzaAsset = AssetImage('images/pizza0.png');
Image image = Image(image: pizzaAsset, width: 400, height: 400);
return Container(
child: image,
);
}
}
Which I use elsewhere, in order to show the image (code omitted):
),
PizzaImageWidget(),
],
The building gives no errors. Flutter Doctor -v doesn't give any errors, neither does Flutter Analyze -v. The .apk seems to build just fine but when the app opens up on my phone I get the following error in asset_bundle.dart:
Exception has occurred. FlutterError (Unable to load asset: images/pizza0.png)
The error is thrown by this class in the asset_bundle.dart file:
/// An [AssetBundle] that loads resources using platform messages.
class PlatformAssetBundle extends CachingAssetBundle {
@override
Future<ByteData> load(String key) async {
final Uint8List encoded = utf8.encoder.convert(Uri(path: Uri.encodeFull(key)).path);
final ByteData asset =
await BinaryMessages.send('flutter/assets', encoded.buffer.asByteData());
if (asset == null)
throw FlutterError('Unable to load asset: $key');
return asset;
}
}
This happens both for the pizza0.png file as well as the pizza1.png file. The files are visible in the tree structure, both in Windows Explorer as in VS Code. The font assets load without issue.
This is the output I am getting when running Flutter Run -v:
[+1068 ms] I/flutter ( 6489): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════ [ +9 ms] I/flutter ( 6489): The following assertion was thrown resolving an image codec: [ +2 ms] I/flutter ( 6489): Unable to load asset: images/pizza0.png [ +2 ms] I/flutter ( 6489): [ +1 ms] I/flutter ( 6489): When the exception was thrown, this was the stack: [ +2 ms] I/flutter ( 6489): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7) [ +1 ms] I/flutter ( 6489): [ +1 ms] I/flutter ( 6489): #1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:429:44) [ +1 ms] I/flutter ( 6489): [ +1 ms] I/flutter ( 6489): #2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:414:14) [ +1 ms] I/flutter ( 6489): #3 ImageProvider.resolve.. (package:flutter/src/painting/image_provider.dart:267:86) [ +4 ms] I/flutter ( 6489): #4 ImageCache.putIfAbsent (package:flutter/src/painting/image_cache.dart:143:20) [ +3 ms] I/flutter ( 6489): #5 ImageProvider.resolve. (package:flutter/src/painting/image_provider.dart:267:63) [ +3 ms] I/flutter ( 6489): (elided 8 frames from package dart:async) [ +1 ms] I/flutter ( 6489): [ +1 ms] I/flutter ( 6489): Image provider: AssetImage(bundle: null, name: "images/pizza0.png") [ +3 ms] I/flutter ( 6489): Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#20fc8(), name: "images/pizza0.png", [ +1 ms] I/flutter ( 6489): scale: 1.0) [ +2 ms] I/flutter ( 6489): ════════════════════════════════════════════════════════════════════════════════════════════════════
Upvotes: 249
Views: 567823
Reputation: 746
Define assets like a below in pubspec.yaml
assets:
- assets/images/
Now create a folder assets and in it also create images
and font
subfolder in it.
Create a call AppConstants.dart
class AppConstants {
// Base Image Path
static const String baseImagePath = 'assets/images';
}
Now create AppImages
where we will all app images
class AppImages {
static const String baseImagePath = AppConstants.baseImagePath;
static const String profileImg = '$baseImagePath/profile.jpg';
}
Now use it like a below:
Image.asset(AppImages.profileImg),
Upvotes: 0
Reputation: 21
I Just Tried to Save again pubspec.yaml(ctrl+s)
and the problem was solved or flutter pub get
and it worked
Upvotes: 0
Reputation: 101
If you are sure that everything is typed correctly, maybe assets worked before normally but now it's not and hot-restart isn't doing it.
Just close the app and then run your code again
Upvotes: 0
Reputation: 4442
assets:
- assets/
It was working until I upgraded my Flutter version to 3.12.0 .
So the fix was for me to load images was to change it like below
assets:
- assets/images/
Upvotes: 4
Reputation: 1678
In my case I has to change Image.asset
to Image.file
:
from:
Image.asset(r"C:\path\to\file");
to:
Image.file(File(r"C:\path\to\file");
Upvotes: 0
Reputation: 209
if you think everything is ok in pubsepec.yaml . and you wrote the path of the image well then do the following :
1-Fixed By Running :
=>flutter clean
then => flutter pub get
2-close your app and remove it from background apps and
=> run it again
it should appears now ✅
Upvotes: 4
Reputation: 20369
Considering your app will have multiple assets it is better to reference the assets folder and not the asset itself. Ensure you use proper indentations as the pubspec.yaml
is indent sensitive.
flutter:
uses-material-design: true
assets:
- images/
and then you can access the image asset by prefixing the referenced folder path
Image.asset('images/pizza1.png', width:300, height:100)
Note that when an asset’s path is specified in the assets section of pubspec.yaml, the build process looks for any files with the same name in adjacent subdirectories. Such files are then included in the asset bundle along with the specified asset.
See Adding asset variants section in the official flutter docs
Upvotes: 89
Reputation: 3430
In pubspec.yaml check the indent in assets and in assets set lines. In assets line it should be 1 tab or 2 space, and in assets set line, it should be 2 tab or 4 spaces.
assets:
- assets/1.jpeg
[1 Tab or 2 space] assets:
[2 Tab or 4 space] - assets/1.jpeg
After all is done restart the app. Remember Don't use hot reload or hot restart. It won't work.
Upvotes: 1
Reputation: 309
The one thing that was missing from all of these (many duplicates) answers (for android) was this - The pubspec.yaml file needed (for me at least) to reference the asset file using direct reference (note the './' below):
flutter:
uses-material-design: true
assets:
- ./assets/images/
Note that this assumes your assets/images folders are in the root of the project (the same folder that pubspec.yaml is in). This will allow any image in the images folder to be accessible:
child: Image(image: AssetImage("assets/images/Players.png"))
Upvotes: 1
Reputation: 365
first Check assets path in pubspec.yaml and also run flutter clean Command
Upvotes: 1
Reputation: 37
If everything is as it should be and problem still exist.
Here is my suggestion :
Write specified path in "pubspec.yaml".
assets:
- assets/images/x.png
After pub get, yellow line will appear to tell you file doesn't exist.
Then Refactoring your file name will make disappear that yellow line and ide will recognize your existing file.
Hope it helps.
Upvotes: 0
Reputation: 6928
If you are working in a project with many modules could be the case of your module is not accessing the right assets folders. To fix this you have to specify your package name:
Using Flutter SVG
SvgPicture.asset("assets/images/image1.svg", package: "<my_package_name>", width: 100, height: 100,),
Using Image.asset
Image.asset(AssetImage("assets/images/image1.png").assetName, package: "<my_package_name>",);
and don't forget of specifying your assets in pubspec.yaml
:
flutter:
uses-material-design: true
assets:
- assets/
- assets/images/
Refer to this question for further details
Upvotes: 0
Reputation: 401
I have facing this problem. I do flutter clean
, I do Hot Restart
, check the pubspec.yaml
. But everything seems fine.
My problem is at the file name, please check your lower case and upper case of your filename.
My problem is like this.
file name
images/Pizza0.png
error
AssetImage pizzaAsset = AssetImage('images/pizza0.png');
work
AssetImage pizzaAsset = AssetImage('images/Pizza0.png');
Upvotes: 1
Reputation: 181
This maybe happens because Windows OS uses \ as a directory separator. you can do this:
You can create a “raw” string by prefixing it with r:
AssetImage(r'images\icon.png')
or
use the forward slash /
AssetImage('images/icon.png')
Upvotes: 0
Reputation: 389
Image.asset('images/heart.png', fit: BoxFit.cover,width: 450, ),
Setting the width worked for me.
Upvotes: 0
Reputation: 103541
You should consider the indentation for assets
flutter:
assets:
- images/pizza1.png
- images/pizza0.png
More details:
flutter:
[2 whitespaces or 1 tab]assets:
[4 whitespaces or 2 tabs]- images/pizza1.png
[4 whitespaces or 2 tabs]- images/pizza0.png
After all this, you can make a hot-restart.
Upvotes: 358
Reputation: 99
I was having same problem and I found no problem in pubspec.yaml. However, restarting vscode worked for me
Upvotes: 0
Reputation: 332
For Android Studio Bumblebee 2021.1.1: If you have your asset path in pubspec.yaml file set to 'images/' or whatever naming you have preferred then
flutter clean
OR you can go to Tools
-> Flutter
-> Flutter clean
& then hot-restart should fix the problem.
Upvotes: 0
Reputation: 1313
There is clearly some sort of flutter bug. This is my directory structure:
<project>/assets/images/myimage.png
This is what I have in pubspec.yaml:
flutter:
uses-material-design: true
assets:
- assets/images/
And this is how it used to work and still works when I compile for web:
const DecorationImage(image: AssetImage("images/myimage.png")
But it will only work when I compile for ios like this:
const DecorationImage(image: AssetImage("assets/images/myimage.png")
Luckily adding "assets/" as a prefix works now in all cases.
Upvotes: 5
Reputation: 1829
Some times cache will create a problem so first run
flutter clean
after this run
flutter pub get
Upvotes: 12
Reputation: 577
After you did all things and still not working, try:
flutter clean
flutter pub get
sometimes after updating pubspec.yaml file, it can not run pub get although it shows it is running.
try commands above
Upvotes: 6
Reputation: 671
One more answer in the mix:
My pubspec.yaml looked like this:
flutter:
assets:
- assets/us_defs/
- assets/eu_defs/
- assets/images/
and in the invoking code:
Center(
child: Image(
image: AssetImage('assets/images/<name.png>')
)
)
(The *_defs
folders contain json files for various other purposes and I can load them just fine.)
But, the image wouldn't load, no matter what I tried. Checked and double checked the indent spacing, spelling, invoked flutter clean
and flutter pub get
, cold started the app, etc. Tried referencing 'images/<name.png>'
vs 'assets/images/<name.png>'
.
Nada.
Finally, I lifted the images
folder to the top level under the project folder:
flutter:
assets:
- assets/us_defs/
- assets/eu_defs/
- images/ <-- now a top level folder
and in the invoking code:
Center(
child: Image(
image: AssetImage('images/<name.png>');
)
)
... and that worked.
I have no idea why.
Now, I'd rather keep the images
folder in assets
since it fits my sensibilities, but if this reorg gets me going, I'll live with it.
Upvotes: 3
Reputation: 7188
In my case a restart didn't help.
It did worked!
Upvotes: 9
Reputation: 3284
If everything is ok, correct path, correct pubspec spaces, etc, the last thing that could cause this is cache. You can close the simulator and start your application again, it helps for my case.
Upvotes: 3
Reputation: 981
using
Image.asset( 'assets\\images\\logo.png')
worked for me, need to specify the relative image path in puspec.yaml file
Upvotes: 0
Reputation: 1420
This error occurs in when images are not properly updated in pubspec.yaml
Follow the steps to add a image to flutter:
1)create assets folder in project(inplace of assets you can create as your wish like images or else).
2)add images into assets folder(or drag and drop image to assets).
follow the above picture: create a assets dependency and add a images which are already available in assets folder and run command from terminal pubget or press ctrl+s to save it will run and update images ,or press the download arrow which appears in top to update images, once updated successfully in output console you can see exitcode 0.
Upvotes: 0
Reputation: 155
The only thing that worked for me to mention THE WHOLE PATH in the CODE. That is you must mention the image path from the root directory on the code page, in YAML it works with the top-level directory.
You probably can't get away only with the main directory path in code, I have tried a lot and that's the only thing that works.
hope it solved the issue and saved your time.
The 1st image is of code and the second is of the yaml.
Upvotes: 5