Flutter/Dart copyCrop Function Exception: Could not instantiate image codec - flutter

I want to display a cropped Image in Flutter. I use the Image.memory Widget. When I use the orginal image there is no Problem.
var tempStore = await ImagePicker.pickImage(source: ImageSource.camera);
List<int> byteListe = await tempStore.readAsBytes();
image = dartimage.Image.fromBytes(400, 400, byteList);
But after I used the copyCrop() Function I get an Exception..
https://pub.dev/documentation/image/latest/image/copyCrop.html
cropImage = dartimage.copyCrop(image, 4, 0, 100, 100);
Expanded(
child: Container(
child: cropImage != null ? Image.memory(cropImage.getBytes()): Text('No Image'),
),
),
This is the Exception!
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following _Exception was thrown while resolving an image:
Exception: Could not instantiate image codec.
When the exception was thrown, this was the stack:
#0 _futurize (dart:ui/painting.dart:4304:5)
#1 instantiateImageCodec (dart:ui/painting.dart:1682:10)
#2 PaintingBinding.instantiateImageCodec (package:flutter/src/painting/binding.dart:88:12)
#3 MemoryImage._loadAsync (package:flutter/src/painting/image_provider.dart:714:18)
#4 MemoryImage.load (package:flutter/src/painting/image_provider.dart:706:14)
...
Image provider: MemoryImage(_Uint8ArrayView#a573e, scale: 1.0)
Image configuration: ImageConfiguration(bundle: PlatformAssetBundle#c13af(), devicePixelRatio: 4.0, locale: de_DE, textDirection: TextDirection.ltr, platform: android)
Image key: MemoryImage(_Uint8ArrayView#a573e, scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════

Related

WMS layer failed to load on flutter-map

Getting an error, When I was trying to load the WMS layer from GeoServer. It was work since flutter_map: ^0.14.0 .
Today, I update the flutter_map package to flutter_map: ^3.0.0 and it's broken. Thrown an error Exception: Invalid image data . And alongside I used Mapbox for styling the map, and Mapbox works great.
Thrown error:
======== Exception caught by image resource service ================================================
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data
When the exception was thrown, this was the stack:
#0 _futurize (dart:ui/painting.dart:5886:5)
#1 ImageDescriptor.encoded (dart:ui/painting.dart:5741:12)
#2 instantiateImageCodecFromBuffer (dart:ui/painting.dart:2092:60)
#3 PaintingBinding.instantiateImageCodecFromBuffer (package:flutter/src/painting/binding.dart:153:15)
#4 FMNetworkNoRetryImageProvider._loadAsync (package:flutter_map/src/layer/tile_layer/tile_provider/network_no_retry_image_provider.dart:89:20)
<asynchronous suspension>
Image provider: FMNetworkNoRetryImageProvider()
Image key: FMNetworkNoRetryImageProvider()
====================================================================================================
Code:
FlutterMap(
mapController: _mapController,
options: MapOptions(
center: LatLng(51.165691, 10.451526),
zoom: 6,
interactiveFlags: ~InteractiveFlag.rotate,
),
children: [
//Mapbox URL that represents the map style for the radar screen
TileLayer(
urlTemplate:
"https://api.mapbox.com/styles/v1/spektergmbh/cl8ec8kg30****ijjpa6cq/tiles/256/{z}/{x}/{y}#2x?access_token=pk.eyJ1Ijoic3Bla3Rlcmdt****J9.jpamQ8Yl4Wr-xisbkw1a1A",
additionalOptions: {
'accessToken':
'pk.eyJ1Ijoic3Bla3RlcmdtYmg***',
'id': 'mapbox.streets',
},
),
TileLayer(
opacity: _opacity,
backgroundColor: new Color.fromRGBO(0, 0, 0, 0),
wmsOptions: WMSTileLayerOptions(
baseUrl:
'https://***/geoserver/dwd/wms?time=' +
_timeFrames[_count],
layers: ['dwd:WN-SKT'],
version: '1.1.1',
transparent: true,
format: 'image/png',
)),
MarkerLayer(
markers: _markers.length != 0 ? _markers : [],
),
]),

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

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/

Why showcaseview throws error on first try?

Hey I am using ShowCaseView in my Flutterapp. When I first open my app, after registration there is no showcase, not even the icon which should be 'showcased' is shown. But when I am closing the app and opening it again it works just fine.
Thats the code referring to showcase:
class _HomeSearchPageState extends State<HomeSearchPage> {
final keyOne = GlobalKey();
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) => ShowCaseWidget.of(context).startShowCase([
keyOne,
]),
);
}
And now the scaffold:
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(getTopBarSize()),
child: AppBar(
automaticallyImplyLeading: false,
title: Text(
'username',
style: TextStyle(fontSize: 14),
),
actions: <Widget>[
Showcase(
key: keyOne,
description: 'test',
child: IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch())
.whenComplete(() => setName());
}),
),
],
),
),)
I did exactly the same as in the Github example but still it throws this error the first time:
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building IconTheme(color: Color(0xffffffff)):
The getter 'activeWidgetIds' was called on null.
Receiver: null
Tried calling: activeWidgetIds
The relevant error-causing widget was
AppBar
lib\Views\HomeSearchPage.dart:182
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 ShowCaseWidget.activeTargetWidget
package:showcaseview/showcase_widget.dart:51
#2 _ShowcaseState.showOverlay
package:showcaseview/showcase.dart:171
#3 _ShowcaseState.didChangeDependencies
package:showcaseview/showcase.dart:164
#4 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4786
════════ Exception caught by rendering library ═════════════════════════════════
Each child must be laid out exactly once.
The relevant error-causing widget was
AppBar
lib\Views\HomeSearchPage.dart:182
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by scheduler library ═════════════════════════════════
Exception: Please provide ShowCaseView context
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 6224 pos 12: '_children.contains(child)': is not true.
The relevant error-causing widget was
AppBar
lib\Views\HomeSearchPage.dart:182
════════════════════════════════════════════════════════════════════════════════
These errors are kind a looped, so the debug console shows them all the time.
The only difference between the first app opening and the second one is: In the first one the user enters a registrationpage and after this he enters the page with the showcaseview. In the second the user enters directly the page with the showcaseview. How can this affect the showcase and more accurate why does this throw the errors?
Not sure if we share a similar issue but maybe my answer will help you somehow :). The issue occurs when I navigate to the page where I have Showcase widget, but it does not occur when I navigate "back" to the page from the other page.
Maybe you can check this page "This error is thrown if you haven't wrapped your widget with ShowCaseWidget. This is not the problem with the package itself."
Thus, I tried raising the level of the ShowCaseWidget in the main.dart and the issue was solved.
void main() {
// runApp(MyApp());
runApp(
ShowCaseWidget(
autoPlay: false,
autoPlayDelay: Duration(seconds: 8),
autoPlayLockEnable: false,
builder: Builder(
builder: (context) => MyApp(),
),
onStart: (index, key) {
print('onStart: $index, $key');
},
onComplete: (index, key) {
print('onComplete: $index, $key');
},
),
);
}
So far the app still works well. I will report again here in case any issues occur.

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/

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