Created
March 21, 2024 12:20
-
-
Save Heilum/94f49e224b1291451750bb40cb0bed5e to your computer and use it in GitHub Desktop.
A ImageProvider from the photo's assetId of photo gallery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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