Search code examples
flutterdartriverpodflutter-change-notifierflutter-riverpod

If another variable in ChangeNotifier is changed, will the Consumer's model be updated?


If the following setIntVal is called and notifyListeners(); is executed, is the Text redrawn? intVal is changed but strVal is not.

Similarly, what happens when StateNotifier is used?

class DummyManager with ChangeNotifier {
  DummyManager();

  int intVal = 0;
  String strVal = "";

  void setIntVal(val) {
    intVal = val;
    notifyListeners();
  }
}

Consumer<DummyManager>(
    builder: (context, model, child) {
      return Text(model.strVal);
    },
)

Solution

  • Yes. By default, any change in a notifier rebuilds a consumer.

    But you can optimize this, using select:
    By changing your consumer to:

    Consumer(
      builder: (context, ref, child) {
        final strVal = ref.watch(modelProvider.select((v) => v.strVal));
        return Text(strVal);
      },
    )
    

    Then your widget will rebuild only when that specific value changes.

    Do note that the result is expected to be immutable. As such, avoid retuning lists