I’m working on a Flutter app that retrieves anime data from the Jikan API (https://api.jikan.moe/v4/anime). I’m using CachedNetworkImage to display the anime images, but I’m encountering an error:
Error Message:
Invalid argument(s): No host specified in URI null
Here’s the relevant code snippet:
ListView.builder(
// ... other builder arguments
itemBuilder: (context, index) {
return AnimeDataItme(
imageUrl: animeData.data![index].images!.jpg!.imageUrl.toString(),
);
},
),
// Assuming AnimeDataItme builds the CachedNetworkImage
return CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.fill,
);
//web services
@RestApi(baseUrl: ApiConstants.apiUrl)
abstract class WebServices {
factory WebServices(Dio dio, {String baseUrl}) = _WebServices;
@GET(ApiConstants.apiUrl)
Future<Anime> getAnimeData();
}
//repo
Future<Anime> getAnimeData() async {
try {
final response = await _webServices.getAnimeData();
return response;
} on DioError catch (error) {
print("Error: ${error.message}");
throw Exception("Failed to get data information");
}
}
I’ve tried the following:
- Added http:// before the image URL.
- Ensured null safety throughout the code using the null-conditional operator (?.).
However, the error persists and changes to "http://null" with the first attempt.
I’d appreciate any help from the community in identifying the root cause of the null URL and suggesting solutions to fix this error. Has anyone encountered a similar issue or have any insights into what might be causing the problem?
2
Answers
The problem is with imageUrl, try this
The error clearly states that there are "No host specified in URI null" Which means the imageUrl you are passing is null, and CachedNetworkImage can not find any host in that URL.
Let me explain how,
You have written below code
As I mentioned, in that line .toString is the main issue, as you have added null safety operators on that line and you are still forcefully converting the output into string.
So here what happened is that from the API response, you got null value for certain imageUrl in jpg object, and as you are forcefully converting it to String, that value became "null",
Now this "null" String you are passing to CachedNetworkImage and the CachedNetworkImage will take that value as an actual URL and it will try to find the host(or domain) to fetch the image from its server. In this case it cant find the host from the "null" url.
SOLUTION
You may have null values in API response and we can not do anything about it, But we can handle that null error from our side, You just need to add one error placeholder widget and show some asset image like "No image Found".
For Ex :
FYI : And also make sure you are getting the imageURL properly from the API response, It might be the case where the actual problem will be in your model class while converting the imageUrl from json to model class variable. where it is storing the null value instead of the actual URL