I am passing arguments to my provider like
@riverpod
class FetchProducts extends _$FetchProducts {
@override
Future<List<Product>> build({
required String? specificProductId,
required String? clientUid,
}) async {
List<Product> _productList = [];
if (specificProductId != null) {
final productDataSnapshot = await FirebaseFirestore.instance
.collection('product')
.doc(specificProductId.trim())
.get();
if (productDataSnapshot.exists && productDataSnapshot.data() != null) {
_productList.add(Product.fromMap(productDataSnapshot.data()!));
}
} else if (clientUid != null && clientUid != '') {
final productDataSnapshot = await FirebaseFirestore.instance
.collection('product')
.where('client_uid', isEqualTo: clientUid)
.get();
print(productDataSnapshot.docs.map((data) => data.data()));
for (var pdt in productDataSnapshot.docs) {
_productList.add(Product.fromMap(pdt.data()));
}
} else {
final productDataSnapshot = await FirebaseFirestore.instance.collection('product').get();
for (var pdt in productDataSnapshot.docs) {
_productList.add(Product.fromMap(pdt.data()));
}
}
return _productList;
}
Future<void> createNewProduct(Product pdtData) async {
final newPdt = await FirebaseFirestore.instance.collection('product').add(pdtData.toMap());
Product newProduct = Product.fromMap(newPdt as Map<String, dynamic>);
state = AsyncData([...?state.value, newProduct]);
}
}
As soon as my UI page opens all products are fetched with specificProductId and clientUid as empty.
There is another notifier provider which gives clientUid when a client is chosen in UI. This triggers a widget on the same UI page to fetch products for that specific clientUid.
However, this causes the provider with all the products getting disposed off.
Problem: How to keep the state of the provider with all the products intact when provider is watched by any other widget with different set of parameters, but auto-disposing the provider when the last listener has been removed?
Current Console output looks like –
Provider fetchProductsProvider:FetchProductsProvider#80775(null) was initialized with AsyncLoading<List<Product>>() Provider fetchProductsProvider:FetchProductsProvider#80775(null) updated from AsyncLoading<List<Product>>() to AsyncData<List<Product>>(value: [Instance of 'Product', Instance of 'Product', Instance of 'Product', Instance of 'Product', Instance of 'Product']) // Chosing a client Provider chosenClientUidProvider:AutoDisposeNotifierProviderImpl<ChosenClientUid, String?>#d6c1c updated from to 8C9rnB..............B2sNk0 Provider fetchProductsProvider:FetchProductsProvider#4e744(null) was initialized with AsyncLoading<List<Product>>() Provider fetchProductsProvider:FetchProductsProvider#80775(null) was disposed Provider fetchProductsProvider:FetchProductsProvider#4e744(null) updated from AsyncLoading<List<Product>>() to AsyncData<List<Product>>(value: [Instance of 'Product', Instance of 'Product', Instance of 'Product'])