Baseflow / Baseflow/flutter_cached_network_image

Support async headers (Future) in CachedNetworkImageProvider

Open
#1,020 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
2.6k
Forks
731
Avg merge
3d 9h
Merged PRs (30d)
1

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)

```dart
Future> 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?> 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)
- [x] :iphone: iOS
- [x] :robot: Android

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.