How to solve exception caught by widgets library? - flutter

I want to use cached network image to display images in my flutter app, however it shows this:
═══════ Exception caught by widgets library ═══════════════════════════════════
Invalid argument (onError): Error handler must accept one Object or one Object and a StackTrace as arguments.: Closure: () => Null
The relevant error-causing widget was
CachedNetworkImage
lib/widgets/custom_image.dart:5
════════════════════════════════════════════════════════════════════════════════
custom_image.dart -
import 'package:flutter/material.dart';
Widget cachedNetworkImage(String mediaUrl) {
return CachedNetworkImage(
imageUrl: mediaUrl,
fit: BoxFit.cover,
placeholder: (context, url) => Padding(
child: CircularProgressIndicator(),
padding: EdgeInsets.all(20.0),
),
errorWidget: (context, url, error) => Icon(Icons.error),
);
}
Please help.

After doing some research and trial and error.
I think the issue is in the package. The error you are getting was a
bug in the old version of the HTTP package and I think your
cached_network_image is outdated.
Try flutter pub upgrade, resolve any
dependency conflicts, do flutter clean, and flutter pub get.
Also, make sure your flutter SDK is updated as well.

Wrap your CachedNetworkImage with a Container.
return Container(
width:...,
height:...,
child: CachedNetworkImage(..)));

Related

How to solve NetworkImageLoadException in flutter

I am trying to fetch image using image.network(), not getting result, showing error, actually image address will get in api responses,
code look like this,
Container(
height: double.infinity,
width: MediaQuery.of(context).size.width *0.18,
child: Image.network(
value.recentObservations[index]
["thumbnail"],),)
and error showing like this,
════════ Exception caught by image resource service ════════════════════════════
The following NetworkImageLoadException was thrown resolving an image codec:
How tom resolve this error, comment your references
This is because your server is not allowing to fetch the image url data. So resolve this from server end.
And you can use
errorBuilder
in network image to show any default image when your image gets failed to load into specified widget.
You can use below sample code for errorBuilder.
Image.network(
path.image,
width: 50,
height: 50,
errorBuilder: (BuildContext context, Object exception,
StackTrace? stackTrace) {
return const Text('😒');
},

Is there a way to solve NoSuchMethodError originating from indexedStack when using a list in flutter?

The indexedStack I use to show a series of pictures one after the other is the origination of a noSuchMethod error. I am trying to build the stack using a list in my firebase like this:enter image description here
The relevant code that causes the error is here; channelData is defined as channelData =
Map<String, dynamic>.from(widget.channelSnapshot.data() as Map); where "posts" is the list that holds the sublists with the timestamps and links.
IndexedStack(
index: index,
children: channelData["posts"]
.toList()((doc) {
precacheImage(
NetworkImage(doc["postPicUrl"]), context);
return Padding(
padding: const EdgeInsets.all(0.0),
child: Container(
width: 280,
height: 150,
padding: EdgeInsets.all(7),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(doc["postPicUrl"]),
fit: BoxFit.cover),
)),
);
}).toList(),
)
The error code is here:
Dynamic call of object has no instance method 'call'.
Receiver: Instance of 'List<dynamic>'
Arguments: [Instance of '(dynamic) => Padding']
The relevant error-causing widget was:
Builder
I know that the issue is probably how I'm presenting the list to the indexedStack. The code was working when I was doing the same thing with snapshot.data!.docs.map((doc) as the children of the indexedStack instead of channelData[posts]. I know that indexedstack is the source of the issue because when it is removed the page loads fine, including the widgets also dependent on data from that list. I have tried changing the location of the .toList(); changing which widget is shown first, etc, but there really aren't any similar issues on the internet. Thanks so much in advance for any help.
Problem:
You're missing the .map() statement before the ((doc) {...}).toList() callback.
From your current code, you're attempting to call a method on the List which is why the error message says:
Dynamic call of object has no instance method 'call'.
Receiver: Instance of 'List<dynamic>'
Solution:
Map the List by calling .map() on the list and passing it the callback.
Change block of code:
IndexedStack(
index: index,
children: channelData["posts"]
.toList()((doc) {
...
}).toList(),
)
to this:
IndexedStack(
index: index,
children: channelData["posts"]
.toList().map<Widget>((doc) {
...
}).toList(),
)

Cached Network SVG Image

I want to display an SVG picture retrieved from network with the help of Flutter_SVG package and use the same picture in different pages with the Hero widget. But each time I use SvgPicture.network() widget, it loads the image again and again from network;
Page 1 & Page 2
Hero(
tag: 'randomTag',
child: SvgPicture.network(url),
),
I have tried to combine Cached Network Image dependency with Flutter_SVG package but don't know how to use them as a widget together;
Hero(
tag: 'randomTag',
child: CachedNetworkImage(
imageUrl: url,
imageBuilder: (context, ImageProvider<Object> imageProvider) {
// How to use ImageProvider<Object> with SvgPicture?
}
),
),
svg_cached_network_image dependency is not an option since it is not compatible with other dependencies that I use.
Use flutter_cache_manager to save svg from internet
This line get svg from internet and save it to local, and next time you call it it will get from local
var file = await DefaultCacheManager().getSingleFile(url);
https://pub.dev/documentation/flutter_cache_manager/latest/flutter_cache_manager/BaseCacheManager/getSingleFile.html

cached_network_image throw Invalid image data exception if url is 404

I am using CachedNetworkImage in book list. If image url is wrong or 404, it is throw Invalid image data exception in firebase Crashlytics report. But in app, image in list is showing black container that in written in errorWidget. My question is how I can catch this error instead of throwing exception. You can even get the exception at debug mode.
Now firebase is keeping on sending the email alert, because of repetitive crashes.
CachedNetworkImage(
width: 110.0,
fit: BoxFit.cover,
imageUrl: ebook.thumbnail,
placeholder: (context, url) => Container(color: Colors.black12),
errorWidget: (context, url, error) =>
Container(color: Colors.black12),
)

FadeInImage with unknown image at runtime

I have a FadeInImage in my app, with the image loaded in response to a user action. This means at runtime, I dont know the image, and just want the FadeInImage to not display anything.
If I pass in null for the image, or an empty string, I get a runtime error.
flutter: ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
flutter: The following ArgumentError was thrown resolving an image codec:
flutter: Invalid argument(s): No host specified in URI file:///
Here it the relevant Widget declaration:
Container(
height: 100,
child:FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: _d2apiModel.emblemUrl,
fit: BoxFit.fitWidth,
),
(where _d2apiModel is a Provider which is updated based on user actions).
I know I could put a default image in the asset bundle, copy it out of the bundle to the doc storage, get the file URI for the image, and use that as the default but 1) that seems like overkill, 2) i run into some async issues.
It seems like I am missing something obvious, but I cant figure out the approach. Any suggestions would be appreciated.
You can show a regular Image with kTransparentImage while your provider hasn't been updated, and then show your FadeInImage when it updates:
Container(
height: 100,
child: hasProviderBeenUpdated
? Image.memory(
kTransparentImage,
fit: BoxFit.fitWidth,
)
: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: _d2apiModel.emblemUrl,
fit: BoxFit.fitWidth,
),
),