Home > Enterprise >  Flutter - RiverPod Newbie. How to watch StateNotifier in my view
Flutter - RiverPod Newbie. How to watch StateNotifier in my view

Time:12-21

I have a Recipe Repository that get recipes from FireStore

class RecipeRepository {

  Future<List<Recipe>> readAll() async {
    final snap = await _recipeRef.get();
    return snap.docs.map((doc) => doc.data()).toList();
  }
}

Here I'm returning the Repository as a Provider

final recipeRepositoryProvider =
    Provider<RecipeRepository>((ref) => RecipeRepository());

Here I have a Class that I want to use to control the state of the UI

final recipeAsyncController =
    StateNotifierProvider<RecipeAsyncNotifier, AsyncValue<List<Recipe>>>(
        (ref) => RecipeAsyncNotifier(ref.read));

class RecipeAsyncNotifier extends StateNotifier<AsyncValue<List<Recipe>>> {
  RecipeAsyncNotifier(this._read) : super(const AsyncLoading()) {
    init();
  }
  final Reader _read;

  init() async {
    final recipes = await _read(recipeRepositoryProvider).readAll();
    state = AsyncData(recipes);
  }
}

As you can see I'm wrapping the recipeRepositoryProvider on a read.

In my UI I want to View the recipe list

    return Consumer(
      builder: (context, watch, child) {
        return watch(recipeAsyncController).when();
      },
    );

The problem is I'm getting the following error. enter image description here

When trying to access the when async call.

CodePudding user response:

https://pub.dev/documentation/flutter_riverpod/latest/flutter_riverpod/Consumer-class.html

the second parameter in builder function is actually a ref object.

  return Consumer(
      builder: (context, ref, child) {
        return ref.watch(recipeAsyncController).when();
      },
    );
  • Related