How to implement a lazy loading behavior outside the Flutter scope? #708
-
I didn't find how to create a kind of question. Tell me please if it's inappropriate I will remove it. I want to read my CDN assets lazily. Does my approach have any flaws? // asset.dart
@freezed
class Asset with _$Asset {
static final ProviderContainer _providerContainer = ProviderContainer();
const factory Asset({
@JsonKey(ignore: true) String? id,
required String parentId,
required String path,
required Devices device,
required DateTime timestamp,
}) = _Asset;
factory Asset.fromJson(Map<String, dynamic> json) => _$AssetFromJson(json);
const Asset._();
Future<Uint8List> get assetAsBytes =>
_providerContainer.read(cdnRepositoryProvider).load(path);
}
// cdn_repository_provider.dart
final cdnRepositoryProvider = Provider.autoDispose<CdnRepository>(
(ref) => CdnRepository(storage: ref.read(firebaseStorageProvider)));
class CdnRepository {
final FirebaseStorage _storage;
CdnRepository({required FirebaseStorage storage}) : _storage = storage;
Future<Uint8List> load(String path) async {
final data = await _storage.ref(path).getData();
return data!.buffer.asUint8List();
}
} P.S. Could you please also briefly explain what is wrong with calling |
Beta Was this translation helpful? Give feedback.
Answered by
rrousselGit
Aug 23, 2021
Replies: 1 comment 2 replies
-
You shouldn't create a ProviderContainer. Instead, consider making a provider: final bytesForAssetPathProvider = FutureProvider.autoDispose.family<Uint8List, String>((ref, path) async {
final repository = ref.watch(cdnRepositoryProvider);
return repository.load(path);
}); |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
rrousselGit
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You shouldn't create a ProviderContainer.
That
assertAsBytes
is also anti-pattern.Instead, consider making a provider: