I have added my asset files in my projects root directory, which contains images, fonts and sounds.
Added the assets in pubspec.yaml
file like this:
flutter:
uses-material-design: true
assets:
- assets/images/
Then I try to add an image through Image.asset
like the code below:
Scaffold(
appBar: AppBar(
leading: Align(
alignment: Alignment.centerRight,
child: Text(
"Uber",
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.w400
),
),
),
),
body: Column(
children: [
Text(
"riyad",
style: TextStyle(color: Colors.black),
),
Image.asset("car_android.png") <-- like this
],
),
);
But it shows me an exception that failed to load the asset:
The following assertion was thrown resolving an image codec:
Unable to load asset: car_android.png
My traceback exception:
════════ Exception caught by image resource service ════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: car_android.png
When the exception was thrown, this was the stack
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:224:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:672:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "car_android.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#243b1(), name: "car_android.png", scale: 1.0)
I tried to run the command flutter clean
to clean the cache and then run the app again, but the same problem occurred again, it failed to load the asset.
Specify Image path as follows
Image.asset("assets/images/car_android.png")
OR
Image(image: AssetImage("assets/images/car_android.png"))
The problem is flutter can't recognize where your image is exactly stored.
If the problem continues then try to do HOT RESTART this will solve your problem.
If you update pubspec.yaml file then run flutter pub get
to update the libraries if your IDE doesn't update it automatically.
Just to push a little further on Harshil Khamar answer which is correct and valid another consideration.
The assets in pubspec.yaml
have to be under flutter:
if you place another entry in between these then it does not know where the assets folder is. It may sound stupid, but I am sure I am not the only one to have done this.
flutter:
uses-material-design: true
generate: true
flutter_intl:
enabled: true
assets:
- assets/images/<<imagename>>
The flutter_intl:
gets in the way as assets now think it is under flutter_intl:
and not flutter:
. If I am the only idiot then okay so be it.
flutter_intl:
enabled: true
flutter:
uses-material-design: true
generate: true
assets:
- assets/images/<<imagename>>
This solves the problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With