Search code examples
flutterdartriverpodriverpod-generator

How to call a method from notifier provider inside riverpod without the parameter specified in build


i have this code

@riverpod
class MoodNotifier extends _$MoodNotifier {
  @override
  Future<MoodType?> build(DateTime date) async {
    final healthService = ref.watch(healthServiceProvider);
    final response = await healthService.moodDateGet(
      date: DateFormat('yyyy-MM-dd').format(date),
    );
    MoodType? mood = MoodType.values
        .firstWhereOrNull((element) => element.text == response.body);
    return mood;
  }

  Future postMood(MoodType moodType) async {
    final healthService = ref.watch(healthServiceProvider);
    final response = await healthService.moodPost(
        body: UserMoodRequest(
      moodType: moodType.toUserMoodReq,
    ));
    log(response.toString());
    Logger.root.log(Level.INFO, response);
  }
}

so when i called the postMood, i need to write something like

ref.read(moodNotifierProvider(DateTime.now()).notifier).postMood(MoodType.happy);

so i want to avoid using the date parameter to be passed whenever i use other method.. how can i do this with riverpod


Solution

  • In general, this is the whole point of using parameters, that in this way your supplier becomes individual based on the parameter.

    However, you can use a simple provider (Provider or StateProvider) to store the required date there:

    For example:

    final dateProvider = Provider<DateTime>((ref) => DateTime.now());
    

    And then in the build method:

    @riverpod
    class MoodNotifier extends _$MoodNotifier {
      @override
      Future<MoodType?> build() async {
        final healthService = ref.watch(healthServiceProvider);
    
        final date = ref.watch(dateProvider); // <-- here
        final response = await healthService.moodDateGet(
          date: DateFormat('yyyy-MM-dd').format(date),
        );
        MoodType? mood = MoodType.values
            .firstWhereOrNull((element) => element.text == response.body);
        return mood;
      }
    }