rrousselGit / state_notifier

ValueNotifier, but outside Flutter and with some extra perks
MIT License
311 stars 28 forks source link

react to state change #8

Closed smiLLe closed 4 years ago

smiLLe commented 4 years ago

Imagine you listen to a UserState where there is a user or null. If the UserState changed, i want to start Async tasks etc. in one of the listening StateNotifier.

As i am not allowed to call .read from .update. what is the best way to react on something?

/// this wil throw in setText, because .read is not allowed
class Bar extends StateNotifier<String> with LocatorMixin {
  Bar() : super('hello');

  @override
  void update(T Function<T>() watch) {
    watch<int>();
    setText();
  }

  void setText() {
    state = 'hello ${read<int>()}';
    read<Logger>().log(state);
  }
}

One possible way:

/// this wil throw in setText, because .read is not allowed
class Bar extends StateNotifier<String> with LocatorMixin {
  Bar() : super('hello');

  int i = 0;
  Logger logger;

  @override
  void update(T Function<T>() watch) {
    i = watch<int>();
    logger = watch<Logger>();
    setText();
  }

  void setText() {
    state = 'hello ${i}';
    logger.log(state);
  }
}
rrousselGit commented 4 years ago

Sounds like an abstraction issue. setText should call watch here

rrousselGit commented 4 years ago

The solution you found is the correct one 👌 Alternatively, you can pass watch to setText