-
-
Notifications
You must be signed in to change notification settings - Fork 713
Open
Description
🏗 Enhancement Proposal
Add support for passing headers
in CachedNetworkImageProvider
as a Future
.
Pitch
In many cases, the required headers include an authentication token that must be retrieved from an API request. Allowing headers
to be provided as a Future
would enable developers to fully leverage the ImageProvider
mechanism while still handling async token retrieval.
This would also allow the use of placeholders during loading, and placeholders or error widgets in case of failures (including errors that may occur while fetching the token).
In my use case I implemented a custom workaround, but I have to manually supply an image provider while getting token (or if an error occurs while fetching it)
Future<ImageProvider<Object>> makeAauthenticatedImageProvider(
String? path,
) async {
if (path == null) throw MissingPathException();
if (path.isEmpty) throw MissingPathException();
final token = await authenticator.token; // authenticator provide always a valid token so it can renews it automatically
final url = baseUrl.append(path: path);
return CachedNetworkImageProvider(
url.toString(),
headers: {'Authorization': 'Bearer $token'},
errorListener: (e) =>
_logger.info('Error while loading image at url $url', error: e),
);
}
class AsyncImageProviderWidget extends StatelessWidget {
const AsyncImageProviderWidget({
super.key,
required this.imageProviderFuture,
required this.onImageProvider,
});
final Future<ImageProvider<Object>?> imageProviderFuture;
final ImageProviderBuilder onImageProvider;
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: imageProviderFuture,
builder: (context, snapshot) => onImageProvider(context, snapshot.data),
);
}
}
// And use them like this:
AsyncImageProviderWidget(
imageProviderFuture: makeAauthenticatedImageProvider('https://.....'),
onImageProvider: (_, ip) {
if (ip == null) return const SizedBox.square(dimension: 80.0);
return Image(
height: 80.0,
image: ip,
errorBuilder: (context, error, stackTrace) => PlaceholderImage(),
);
},
),
Platforms affected (mark all that apply)
- 📱 iOS
- 🤖 Android
Metadata
Metadata
Assignees
Labels
No labels