Home > Mobile >  (Flutter/Riverpod) the example of StateProvider document was not updated
(Flutter/Riverpod) the example of StateProvider document was not updated

Time:12-06

The example of StateProvider of Riverod is not yet updated.

https://pub.dev/documentation/riverpod/latest/riverpod/StateProvider-class.html

final selectedProductIdProvider = StateProvider<String?>((ref) => null);
final productsProvider = StateNotifierProvider<ProductsNotifier, List<Product>>(
    (ref) => ProductsNotifier());

Widget build(BuildContext context, WidgetRef ref) {
  final List<Product> products = ref.watch(productsProvider);
  final selectedProductId = ref.watch(selectedProductIdProvider);

  return ListView(
    children: [
      for (final product in products)
        GestureDetector(
          onTap: () => selectedProductId.state = product.id,
          child: ProductItem(
            product: product,
            isSelected: selectedProductId.state == product.id,
          ),
        ),
    ],
  );
}

Now that Riverpod has become v1 stable, the above code does not work any more.

Is the following the correct code for Riverpod v1 stable?

final selectedProductIdProvider = StateProvider<String?>((ref) => null);
final productsProvider = StateNotifierProvider<ProductsNotifier, List<Product>>(
    (ref) => ProductsNotifier());

class Foo2 extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final List<Product> products = ref.watch(productsProvider);
    final String? selectedProductId = ref.watch(selectedProductIdProvider);
    final StateController<String?> selectedProductIdController =
        ref.watch(selectedProductIdProvider.notifier);

    return ListView(
      children: [
        for (final product in products)
          GestureDetector(
            onTap: () => selectedProductIdController.state = product.id,
            child: ProductItem(
              product: product,
              isSelected: selectedProductId == product.id,
            ),
          ),
      ],
    );
  }
}

CodePudding user response:

Oopsy!

Your code is correct, although you don't have to obtain the notifier inside build and could do it within onTap:

onTap: () => ref.read(selectedProductIdProvider.notifier).state = product.id,
  • Related