[flutter] FlutterError: Unable to load asset

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 yaml file, 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(),
      ],

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): ----------------------------------------------------------------------------------------------------

This question is related to flutter assets

The answer is


I ran into this issue and very nearly gave up on Flutter until I stumbled upon the cause. In my case what I was doing was along the following lines

static Future<String> resourceText(String resName) async
{
 try
 { 
  ZLibCodec zlc = new ZLibCodec(gzip:false,raw:true,level:9);
  var data= await rootBundle.load('assets/path/to/$resName');
  String result = new 
  String.fromCharCodes(zlc.decode(puzzleData.buffer.asUint8List()));
  return puzzle;
 } catch(e)
 {
  debugPrint('Resource Error $resName $e');
  return ''; 
 } 
}

static Future<String> fallBackText(String textName) async
{
 if (testCondtion) return 'Some Required Text';
 else return resourceText('default');
} 

where Some Required Text was a text string sent back if the testCondition was being met. Failing that I was trying to pick up default text from the app resources and send that back instead. My mistake was in the line return resourceText('default');. After changing it to read return await resourceText('default') things worked just as expected.

This issue arises from the fact that rootBundle.load operates asynchronously. In order to return its results correctly we need to await their availability which I had failed to do. It strikes me as slightly surprising that neither the Flutter VSCode plugin nor the Flutter build process flag up this as an error. While there may well be other reasons why rootBundle.load fails this answer will, hopefully, help others who are running into mysterious asset load failures in Flutter.


Make sure the file names do not contain special characters such as ñ for example


I had the same issue I corrected it, you just need to put the two(uses-material-design: true and assets) in the same column and click in the upgrade dependencies but before restart android studio.

screenshot


Dec 25th, 2019 :

Whoever facing issue regarding Image not showing in Flutter , let me give you simple checkpoints :

  1. Image.asset('assets/images/photo1.png'); -- here make sure dont use / (forward slash ) before assets.
  2. YAML file always be clear dont use space , instead use TAB.
  3. YAML file add entries for assets. as mentioned in above comment.

First point is very important


Actually the problem is in pubspec.yaml, I put all images to assets/images/ and

This wrong way

flutter:
  uses-material-design: true
  assets:
  - images/

Correct

flutter:
  uses-material-design: true
  assets:
  - assets/images/

This issue still existed in my case even after, flutter clean (deletes build folder) and proper indentations in yaml file

It got fixed by itself, as it could be an issue related to Android Studio.

Fix 1) Restart the emulator in Cold Boot mode, In Android Studio, after clicking List Virtual Devices button, click Drop down arrow (last icon next to edit icon) => Choose Cold Boot Now option. If issue still exist, follow as below

Fix 2) After changing the emulator virtual device as a workaround,

For Example : From Nexus 6 to Pixel emulator

--happy coding!


Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app.

Here is an example:

flutter:
  assets:
    - assets/my_icon.png
    - assets/background.png

To include all assets under a directory, specify the directory name with the / character at the end:

flutter:
  assets:
    - directory/
    - directory/subdirectory/

For more info, see https://flutter.dev/docs/development/ui/assets-and-images


This is issue has almost driven me nut in the past. To buttress what others have said, after making sure that all the indentations on the yaml file has been corrected and the problem persist, run a 'flutter clean' command at the terminal in Android studio. As at flutter 1.9, this should fix the issue.


For me,

  1. flutter clean,
  2. Restart the android studio and emulator,
  3. giving full patth in my image

    image: AssetImage(
      './lib/graphics/logo2.png'
       ),
       width: 200,
       height: 200,
     );
    

these three steps did the trick.


  1. you should start image path with assets word:

image: AssetImage('assets/images/pizza0.png')

  1. you must add each sub folder in a new line in pubspec.yaml

After declaring correctly in pubspec.yaml, consider giving full path of the image ex.

'assets/images/about_us.png' 

instead of just images/..

worked for me after wasting 2 hours on such a trivial error.


Don't struggle to add the path to each image asset, instead just specify the path to your images directory.
just make sure you use proper indentations as the pubspec.yaml is indent sensitive.

flutter:

  uses-material-design: true
  assets:
    - images/

and you can simply access each image as

  new Image.asset('images/pizza1.png',width:300,height:100)

I was also facing the same issue . The issue on my side was that the image name was having the space in between its name so I updated the image name with the new name that does not have any space.

Image name creating the error was comboclr emtpy no circle.png

I updated this name to comboclr_emtpy_no_circle.png


I had the same error when trying to add an image to a module inside a larger project turns out the Image.asset widget takes a packages parameter that you can specify, after specifying it worked just fine


I also had this problem. I think there is a bug in the way Flutter caches images. My guess is that when you first attempted to load pizza0.png, it wasn't available, and Flutter has cached this failed result. Then, even after adding the correct image, Flutter still assumes it isn't available.

This is all guess-work, based on the fact that I had the same problem, and calling this once on app start fixed the problem for me:

imageCache.clear();

This clears the image cache, meaning that Flutter will then attempt to load the images fresh rather than search the cache.

PS I've also found that you need to call this whenever you change any existing images, for the same reason - Flutter will load the old cached version. The alternative is to rename the image.


Well in case you have changed everything in the indentation part as told and checked for the typo errors but still get an error then you should do this simple which worked for me and it seems this is overlooked by almost everyone

even if you have correct spacing after the assets: you still might be doinbg this one thing wrong

keep the indentation in this order

flutter: <2_spaces>assets: <no_space>- assets/images/image.png

thus it should look like this

flutter:
  assets:
  - assets/images/image.png

Encountered the same issue with a slightly different code. In my case, I was using a "assets" folder subdivided into sub-folders for assets (sprites, audio, UI).

My code was simply at first in pubspec.yaml- alternative would be to detail every single file.

flutter:

  assets:
    - assets

Indentation and flutter clean was not enough to fix it. The files in the sub-folders were not loading by flutter. It seems like flutter needs to be "taken by the hand" and not looking at sub-folders without explicitly asking it to look at them. This worked for me:

flutter:

  assets:
    - assets/sprites/
    - assets/audio/
    - assets/UI/

So I had to detail each folder and each sub-folder that contains assets (mp3, jpg, etc). Doing so made the app work and saved me tons of time as the only solution detailed above would require me to manually list 30+ assets while the code here is just a few lines and easier to maintain.


I haved a similar problem, I fixed here:

uses-material-design: true
 assets:
   - assets/images/

After, do:

Flutter Clean

if you're developing flutter packages, please add package param after image path like this:

AssetImage('images/heart.png', package: 'my_icons') // my_icons is your plugin name, in flutter plugin is also a package.

Here is the link from flutter docs https://flutter.dev/assets-and-images/#from-packages


While I was loading a new image in my asset folder, I just encountered the problem every time.

I run flutter clean & then restarted the Android Studio. Seems like flutter packages caches the asset folder and there is no mechanism to update the cache when a developer adds a new image in the project (Personal thoughts).


Please provide the exact image name(including the extension) as specified in the images folder. A mismatch can trigger this exception.


I put my images in a subdirectory of the assets folder. Whenever I add new images, I restart the application and it works fine.

 assets:
    - assets/sub_folder/

I do this so that I don't have to list each asset name.


In my case a restart didn't help. I had to uninstall the app and then run everything again. It did worked!


I have the same issue. I've just run "$ flutter clean", then everything is OK.

More about this error


My issue was nested folders.

I had my image in assets/images/logo/xyz.png and thought that - assets/images/ would catch all subfolders.

You have to explicitly add each nested subfolder

Solution: - assets/images/logo/ etc.


inside pubspec.yaml, DON'T USE TAB!

flutter:
<space><space>assets:
<space><space><space><space>assets/

example:

flutter:
  assets:
    assets/