Flutter/Riverpod: Call method within StateNotifier from another StateNotifier

Viewed 1880

How can I call the method of one StateNotifier from another StateNotifier? I want to call addNewHabit (in the top class) from submitData (in the lower class).

Here are the bodies of the classes:

class HabitStateNotifier extends StateNotifier<List<Habit>> {
  HabitStateNotifier(state) : super(state ?? []);

  void startAddNewHabit(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (_) {
          return NewHabit();
        });
  }

  //this one right here
  void addNewHabit(String title) {
    final newHabit = Habit(title: title);
    state.add(newHabit);
  }

  void deleteHabit(String id) {
    state.removeWhere((habit) => habit.id == id);
  }
}

and

class TitleControllerStateNotifier
    extends StateNotifier<TextEditingController> {
  TitleControllerStateNotifier(state) : super(state);

  void submitData() {
    if (state.text.isEmpty) {
      return;
    } else {
      //call 'addNewHabit' from above class
    }
  }
}

What is the correct way to do this?

2 Answers

Technically, not a recommended pattern to use as StateNotifiers are controllers and you shouldn't really be calling controllers inside controllers.

But this is pretty easy to accomplish as you can read other providers inside a provider.

final habitProvider = StateNotifierProvider((ref) => HabitStateNotifier());

final userControllerProvider = StateNotifierProvider((ref) {
  return UserController(
   
    habitProvider : ref.read(habitProvider),
  );
});

And then use the reference and call

class TitleControllerStateNotifier
    extends StateNotifier<TextEditingController> {
  TitleControllerStateNotifier(state, HabitStateNotifier habitProvider) :
  habit = habitProvider, 
  super(state);

  final HabitStateNotifier habit;


  void submitData() {
    if (state.text.isEmpty) {
      return;
    } else {
      habit.addNewHabit(state.text);
    }
  }
}

Set up a StateNotifierProvider (from Riverpod), which will give you back a StateNotifier after running the create callback. This callback has a (ref) parameter on which you can call ref.read and ref.watch to fetch other providers in either non-depending or depending mode.

Related