Loading image in Flutter | Path from content root doesn't work, but absolute path works - flutter

Very simple app, the image is in project/images folder.
When I try to load it from the relative path:
'images/diamond.png'
the image doesn't load.
When I do it from the absolute path: '/Users/MacBookAir/StudioProjects/secondtry_iamrich/images/diamond.png'
it does.
Why is this? Can anyone please help?
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: const Text('I am Rich'),
backgroundColor: Colors.blueGrey[900],
),
body: const Center(
child: Image(
image: AssetImage('images/diamond.png'),
),
),
),
),
);
}
This is the error it is providing:
======= Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: images/diamond.png
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:237:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:658:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "images/diamond.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#99cb5(), name: "images/diamond.png", scale: 1.0)
====================================================================================================

Do not forgot to add image folder path to your pubspec.ymal folder like
assets:
- assets/images/
- assets/images/icons/
- assets/loader.json
Use this plugin in your android studio it will auto generate your all assets no need to write path.
Use it like this
Image.asset(Assets.imagesNoDataFound, scale: 3.5)

Uncomment and change the asset section in your pubspect.yaml file can fix it.
assets:
- images/

Related

[ERROR: Unable to load asset: assets/audios/note1.wav in flutter

I have this question. My code actually working but when I click my button there is no new sound. I actually change the name of directory folder but it didn't work.
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:math';
void main() => runApp(XylophoneApp());
class XylophoneApp extends StatelessWidget {
void playSound () {
final player = AudioPlayer();
int soundNumber = Random().nextInt(5) + 1;
player.setSource(AssetSource('sounds/note$soundNumber.wav'));
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child:TextButton
(onPressed: () {
playSound();
},
child:const Text('Click Me')),
),
),
),
);
}
}
Here is the result:
E/flutter ( 8119): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)]
Unhandled Exception: Unable to load asset: assets/audios/note1.wav
E/flutter ( 8119): #0 PlatformAssetBundle.load
(package:flutter/src/services/asset_bundle.dart:237:7)
E/flutter ( 8119): <asynchronous suspension>
yaml file :
assets:
- assets/sounds/
You have to add this file in assets section in pubspec.yaml file
assets:
- assets/audios/note1.wav
try to move your sub audio folder out of your former asset folder that comes by default . and place it direct to your project new folder like lib folder in the first level
sometimes flutter does not see the external files .
and for better work done clean your engine .
As I'm working in the Xylophone project
I did this to run my APP:
You can add new project and then rewrite your code line by line and debug it
probably it is because of some change that you have done.
Change the package I recommend you to add the new package in new projects
PS: If you are in windows before everything quit the Android Studio from the Task Manager and shut down your computer then start everything from the beginning
If you find new solution let me know
Thank you

Unable to load Image asset exception thrown in Flutter

Here's my code:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text('I AM RICH'),
backgroundColor: Colors.blueGrey[900],
),
body: Center(
child: Image(
image: AssetImage('images/diamond.png'),
),
),
),
),
);
}
THIS IS THE EXCEPTION I AM GETTING.
My pubspec.yaml file follows proper indentation.
======= Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: images/diamond.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: "images/diamond.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#a2375(), name: "images/diamond.png", scale: 1.0)
====================================================================================================
I assume that your image is under the assets folder. So, you need to call image like this:
AssetImage('assets/images/diamond.png')
And be sure that you wrote this correctly in your pubspec.yaml:
assets:
- assets/images/
make changes in your pubspec.yaml file
add this line to import all the files present in images folder
assets:
- images/
for showing image you can use any one of the code shown below
Image(image: AssetImage('images/diamond.png')),
or
Image.asset('images/diamond.png'),
Add asset path in pubspec.yaml as
assets:
- images/diamond.png
or you can also add parent folder path
assets:
- images/
Here's my pubspec.yaml file:
name: i_am_rich
description: Show off your wealth.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images\
Ultimately the problem is with typing mistake, "images" should be "images/"
Interesting how pub get executes with an exit code of 0 even after typing error.

Image does not show on leading part of list tile when using Circle Avatar and back ground image

I am building this app and just have a small UI problem. I am using a ListView builder. On the leading part of the tile, I want a circular icon to display with the desired image.
I believe my implementation is correct but when I run my code the circle avatar does come out on the leading part of the tile but it does not display the desired image. Instead, it just shows a blue circle on the leading end of each tile.
I am also getting an exception from the terminal. I will attach my code and the exception that I am getting. I would really appreciate suggestions from anyone. Thank you all!
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
List<String> titles = ["Covid-19 Cases", "Covid-19 Vaccine Tracker",
"Dr. John Campbell Youtube Channel", "Medcram YouTube Channel"];
List<String> files = ["cases.png", "vaccineIMG.png", "dr.johncampbell.png",
"Medcram.png"];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black54,
appBar: AppBar(
backgroundColor: Colors.redAccent,
title: Text("Your Covid-19 Briefing"),
),
body: ListView.builder(
itemCount: titles.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
onTap: () {
_launchUrl(index);
},
title: Text(
titles[index],
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
letterSpacing: 1.0,
color: Colors.black,
),
),
leading: CircleAvatar(
backgroundImage: AssetImage('assets/${files[index]}'),
),
),
);
}
),
),
);
}
_launchUrl(index) async {
List<String> _urlsToLaunch = [
"https://www.worldometers.info/coronavirus/",
"https://www.nytimes.com/interactive/2020/science/coronavirus-vaccine-tracker.html",
"https://www.youtube.com/c/Campbellteaching/videos/",
"https://www.youtube.com/c/Medcram/videos"
];
if (await canLaunch(_urlsToLaunch[index])) {
await launch(_urlsToLaunch[index]);
} else {
throw "Could not open $_urlsToLaunch";
}
}
}
Error:
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: assets/cases.png
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:664:31)
#2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:648:14)
#3 ImageProvider.resolveStreamForKey.<anonymous closure> (package:flutter/src/painting/image_provider.dart:501:13)
...
Image provider: AssetImage(bundle: null, name: "assets/cases.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#e7274(), name: "assets/cases.png", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by image resource service ════════════════════════════════════════════════
Unable to load asset: assets/vaccineIMG.png
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by image resource service ════════════════════════════════════════════════
Unable to load asset: assets/dr.johncampbell.png
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by image resource service ════════════════════════════════════════════════
Unable to load asset: assets/Medcram.png
════════════════════════════════════════════════════════════════════════════════════════════════════
pubspec.yaml file:
name: coronavirus_news_updates
description: A new Flutter application.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
url_launcher: ^5.4.11
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
Have you included your assets in your pubspec.yaml file?
flutter:
assets:
- assets/your_image_name.png
or to incude the entire folder:
flutter:
assets:
- assets/

fromCsv returns a cannot open file exception

I am trying to use the ml_algo package to get a dataset using the fromCsv method present in the ml_algo package. I have put the csv file into an asset folder and still get an error.
I have tried all possible ways from flutter clean to invalidate cache and restart and even tried putting it on my phone and I gave the absolute path still it does not work
The following is the dart code:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:ml_dataframe/ml_dataframe.dart';
import 'package:ml_preprocessing/ml_preprocessing.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:permission/permission.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Future<void> initialiseDataframe() async {
/* var permissionsRequested = await Permission.requestSinglePermission(PermissionName.Storage);
print(permissionsRequested);
var permissionsStatus = await Permission.getSinglePermissionStatus(PermissionName.Storage);
print(permissionsStatus.toString());
*/
Directory tempDir = await getTemporaryDirectory();
String tempdir = tempDir.absolute.path;
print(tempdir);
final String directory = await ExtStorage.getExternalStorageDirectory();
print(directory);
final dataFrame = await fromCsv('wheat.csv',
headerExists: true,
columns: [2,3,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25]);
final normaliser = Normalizer();
final transformedDataset = normaliser.process(dataFrame);
print(transformedDataset.toMatrix());
}
#override
void initState() {
initialiseDataframe();
}
}
and here is the pubspec.yaml file
name: linear_regression
description: A new Flutter application.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
ml_dataframe: ^0.0.11
ml_preprocessing: ^5.0.1
ml_algo: ^13.3.7
ext_storage: ^1.0.2
permission: ^0.1.5
path_provider: ^1.6.1
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/res/wheat.csv
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
and the error stack
E/flutter (26103): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'asset/res/wheat.csv' (OS Error: No such file or directory, errno = 2)
E/flutter (26103): #0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9)
E/flutter (26103): #1 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter (26103): #2 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (26103): #3 _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
E/flutter (26103): #4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
E/flutter (26103): #5 Future._propagateToListeners (dart:async/future_impl.dart:709:32)
E/flutter (26103): #6 Future._completeWithValue (dart:async/future_impl.dart:524:5)
E/flutter (26103): #7 Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:554:7)
E/flutter (26103): #8 _rootRun (dart:async/zone.dart:1126:13)
E/flutter (26103): #9 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (26103): #10 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (26103): #11 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
E/flutter (26103): #12 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter (26103): #13 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter (26103):
The problem is that you're trying to access a dataset by using its absolute path, but the path you used is wrong since it's altered during runtime. Unfortunately, Flutter doesn't provide us with the correct absolute path for its assets in runtime.
There is a solution of the issue in ml_algo 15.6.3 and ml_dataframe 0.4.0: you need to read your dataset asset using rootBundle.loadString and feed the resulting string to a DataFrame.fromRawCsv(...) constructor:
import 'package:flutter/services.dart' show rootBundle;
import 'package:ml_dataframe/ml_dataframe.dart';
final rawCsvContent = await rootBundle.loadString('assets/res/wheat.csv');
final samples = DataFrame.fromRawCsv(rawCsvContent);

Exception caught by image resource service, The following assertion was thrown resolving an image codec:

I am trying to load an image into a scroll, but every time it does not load the image due to error:
Exception caught by image resource service The following assertion was thrown resolving an image codec:
Unable to load asset: assets/images/jorge.png
When the exception was thrown, this was the stack:
0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:464:44)
2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:449:14)
...
Image provider: AssetImage(bundle: null, name: "assets/images/jorge.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#dd41f(), name: "assets/images/jorge.png", scale: 1.0)
(2) Exception caught by image resource service
Unable to load asset: assets/images/heitor.png
(3) Exception caught by image resource service
Unable to load asset: assets/images/john.png
I/chatty ( 8763): uid=10206(com.festapp.flutter_app_fest) identical 5 lines
E/AccessibilityBridge( 8763): VirtualView node must not be the root node.
flutter clean was used, besides exchanging images
final User currentUser = User(
id: 0,
name: 'Current User',
imageUrl: 'assets/images/greg.png'
);
//usuários
final User Jorge = User(
id: 1,
name: 'Jorge',
imageUrl: 'assets/images/jorge.png'
);
final User John= User(
id: 2,
name: 'John',
imageUrl: 'assets/images/john.png'
);
final User Heitor = User(
id: 3,
name: 'Heitor',
imageUrl: 'assets/images/heitor.png'
);
final User Gui = User(
id: 4,
name: 'Gui',
imageUrl: 'assets/images/heitor.png'
);
and images use in:
return Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
CircleAvatar(
radius: 35.0,
backgroundImage: AssetImage(favorites[index].imageUrl),
),
SizedBox(
height: 6.0,
),
Text(favorites[index].name, style: TextStyle(
color: Colors.blueGrey,
fontSize: 16.0,
fontWeight: FontWeight.w600,
),
),
],
),
);
Exception caught by image resource service
The following assertion was thrown resolving an image codec:
Unable to load asset: assets/images/jorge.png
When the exception was thrown, this was the stack:
0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:464:44)
2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:449:14)
...
Image provider: AssetImage(bundle: null, name: "assets/images/jorge.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#dd41f(), name: "assets/images/jorge.png", scale: 1.0)
(2) Exception caught by image resource service
Unable to load asset: assets/images/heitor.png
(3) Exception caught by image resource service
Unable to load asset: assets/images/john.png
It seems that these image files aren't in your project:
assets/images/jorge.png
assets/images/john.png
assets/images/heitor.png
Make sure you are doing these things:
Add the images in the folder assets/images/
Specify the images in pubspec.yaml
Execute flutter packages get / tap Packages get from
pubspec.yaml / tap Get dependencies from any dart file.
Use Image.asset() or AssetImage() to show them.
i also faced the same issue,
the solution is to stop the main.dart -by clicking the red button given in taskbar
and then restart it.
sometime its not able to load the images when you add it as fresh
To solve this error, you should check your pubspec.yaml file, either the asset folder is indexed like below or not:
flutter:
[2 whitespaces or 1 tab]assets:
[4 whitespaces or 2 tabs]- assets/images/ #index all files inside images folder
[4 whitespaces or 2 tabs]- assets/images/elephant.jpg #index only elephant.jpg