I am using riverpod to build my app and i am struggling to build a simple add to favorite feature. I have a list of products and a child Consumer widget that is a card with add to favorite button.
When I change the state of the products from the child cards the ui don't rebuild.
here is the git repository https://github.com/nisa10880/riverpod_difficulties
Consumer(
builder: (context, watch, child) =>
watch(getProductsFutureProvider).when(
data: (p) {
final products = watch(productListStateProvider).state;
return ListView.builder(
itemCount: products.length,
itemBuilder: (BuildContext context, int index) =>
ProductCard(product: products[index]));
},
loading: () => CircularProgressIndicator(),
error: (e, s) => Text(e)))
final productServiceProvider = Provider<ProductService>((ref) {
return ProductService();
});
class ProductService {
ProductService();
Future<List<ProductModel>> getAllProducts() async {
await Future.delayed(Duration(seconds: 1));
return [
ProductModel(id: '1', title: 'product 1', isFavorite: false),
ProductModel(id: '2', title: 'product 2', isFavorite: false),
ProductModel(id: '3', title: 'product 3', isFavorite: false),
ProductModel(id: '4', title: 'product 4', isFavorite: false)
];
}
}
final productListStateProvider = StateProvider<List<ProductModel>>((ref) {
return [];
});
final getProductsFutureProvider =
FutureProvider.autoDispose<List<ProductModel>>((ref) async {
ref.maintainState = true;
final evtentService = ref.watch(productServiceProvider);
final products = await evtentService.getAllProducts();
ref.read(productListStateProvider).state = products;
return products;
});
class ProductCard extends ConsumerWidget {
final ProductModel product;
const ProductCard({
@required this.product,
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context, ScopedReader watch) {
return Card(
child: Column(
children: <Widget>[
Text(product.title),
product.isFavorite
? IconButton(
icon: Icon(Icons.favorite),
color: Colors.red,
onPressed: () {
product.isFavorite = !product.isFavorite;
},
)
: IconButton(
icon: Icon(Icons.favorite_border),
color: Colors.black54,
onPressed: () {
product.isFavorite = !product.isFavorite;
},
)
],
));
}
}
The problem is you're updating an inner value of ProductModel
instead of the state (the state is the List<ProductModel>
) so it won't trigger a rebuild, you either try something like this:
onPressed: () {
List<ProductModel> productList = context.read(productListStateProvider).state;
int index = productList.indexWhere((e) => e.id == product.id);
productList[index].isFavorite = !product.isFavorite;
context.read(productListStateProvider).state = productList;
},
or you try to use a ChangeNotifierProvider so you can call notifyListeners() when you feel you made a change to a value