Skip to content

Instantly share code, notes, and snippets.

@Heilum
Created March 21, 2024 12:20
Show Gist options
  • Save Heilum/94f49e224b1291451750bb40cb0bed5e to your computer and use it in GitHub Desktop.
Save Heilum/94f49e224b1291451750bb40cb0bed5e to your computer and use it in GitHub Desktop.
A ImageProvider from the photo's assetId of photo gallery
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:flutter/material.dart';
class PhotoAssetEntityImageProvider extends ImageProvider<String> {
const PhotoAssetEntityImageProvider(this.photoId);
final String photoId;
@override
Future<String> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<String>(photoId);
}
@override
ImageStreamCompleter loadImage(String key, ImageDecoderCallback decode) {
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key),
scale: 1.0,
informationCollector: () sync* {
yield DiagnosticsProperty<ImageProvider>('Image provider', this);
yield DiagnosticsProperty<String>('Image key', key);
},
);
}
Future<ui.Codec> _loadAsync(String key) async {
final AssetEntity? assetEntity = await AssetEntity.fromId(key);
final Uint8List? data = await assetEntity?.originBytes;
if (data != null) {
ui.Codec codec = await ui.instantiateImageCodec(data);
return codec;
}
throw StateError('Failed to load image data for $key');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment