1

I have created these unions using Freezed:

abstract class ProductState with _$ProductState {
  factory ProductState.loading() = ProductLoading;
  factory ProductState.created(Product product) = ProductCreated;
}

Then I have a provider providing a class like this:


final createProductProvider =
    StateNotifierProvider<CreateProductController, ProductState>(
        (ref) => CreateProductController(ref));

class CreateProductController extends StateNotifier<ProductState> {

  createProduct() {
    // create product
    state = ProductCreated(product);
  }
}

In another provider I want to access the underlying data in the union, the product variable.

I have been doing it like this so far:

if(state is ProductCreated) {
   final currentProduct = state.product
}

What is the proper way to do this? Create another provider?

ccnrbrn
  • 126
  • 5
  • Not really an answer but more so a question as you're more readily able to test. Can you `.select` the product off the `ProductState` when you `ref.watch` in your other provider? I don't think so right? And if that's the case, I think creating another provider would benefit in filtering rebuilds to only when `product` changes – Nolence Jul 20 '21 at 16:47
  • I can't use select there. Can't see another way to do this except with "is ProductCreated". – ccnrbrn Jul 20 '21 at 23:18

0 Answers0