I'm trying to develop a Products Favorites system in Flutter with no results. I feel like I'm close to getting it but I'm struggling with some issues. Please does anyone what I'm doing wrong?
First of all, I have an array of ids with the liked products associated with the user. enter image description here
Secondly: this is my ProductService with the method check favorite().
class ProductService extends ChangeNotifier {
bool _isLiked = false;
bool get isLiked => _isLiked;
set isLiked(bool value) {
_isLiked = value;
notifyListeners();
}
Future<bool>? checkFavorite(String? uid, String? productId) async {
final resp = await _firestore.collection('users').doc(uid).get();
Map<String, dynamic> data = resp.data() as Map<String, dynamic>;
var likedProducts = data['liked_products'] as List<dynamic>;
likedProducts.contains(productId) ? _isLiked = true : _isLiked = false;
return _isLiked;
}
Then I have a HomeView where a grid of products is displayed like so:
return Bounce(
duration: const Duration(milliseconds: 150),
onPressed: () => Navigator.pushNamed(context, 'product',
arguments: {
'product': productService.products[index],
'user': loggedInUser
}),
child: ProductCard(
product: productService.products[index],
),
);
The UI result looks like this: enter image description here As you can see the ProductScreen is a layout that receives the user data and the product data as arguments.
Finally, when I go to the product screen and I call the method I print the disliked value to see if it's working. The error that I get is that when I enter the first time the result is always false. Then I go back with the Navigator. pop method and try again. On this occasion, it works fine but the data keep persistent. So when I go back and try to check a non-liked product the result keeps true until the next time that I repeat the process.
This is my code in Product Screen and this is the log with the random results...
class ProductScreen extends StatelessWidget {
const ProductScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final productService = Provider.of<ProductService>(context);
final arguments = ModalRoute.of(context)!.settings.arguments as Map;
final Product product = arguments["product"] as Product;
final UserModel loggedInUser = arguments['user'] as UserModel;
productService.getProductSeller(product.productSeller);
productService.checkFavorite(loggedInUser.uid, product.productId);
print(productService.isLiked);
The main file has all the providers created. I also tried to print the ids to see if I was missing something out but the info is correct. My feeling is like if like the query to the database was a little bit delayed and when it's done it keeps persistent for a while....