rrousselGit / state_notifier

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

Implement notifyListeners method on StateNotifier #10

Closed jamiewest closed 4 years ago

jamiewest commented 4 years ago

I think it would be helpful to have a notifyListeners method on the StateNotifier class to more closely resemble a ChangeNotifier.

This would go along with using StateNotifier in manner similar to ChangeNotifier.

class Person extends StateNotifier<Person> {
   String _email;
   const Person({this.name});

   final String name;

   String get email => _email;

   set email(String value) {
      _email = value;
      notifyListeners();
      // as opposed to... 
      state = this; // would even this work??
   }
}
rrousselGit commented 4 years ago

This is not how you should use StateNotifier. You should not have state that needs to be listened, that is not part of the state variable.

Instead do:

class Person {
  String email = '';
  String name = '';
}

class PersonController extends StateNotifier<Person> {
  PersonController(): super(Person());

  set email(String value) {
    state = Person()
      ..email = value
      ..name = state.name;
  }
}
jamiewest commented 4 years ago

Was this a design choice to have the State and StateNotifier be to separate components or was due to an engineering requirement in order to make things work with provider?

rrousselGit commented 4 years ago

This is a design choice. StateNotifier is not ChangeNotifier, but ValueNotifier

jamiewest commented 4 years ago

I see, that is probably where I am confusing things. Thank you.

venkatd commented 3 years ago

Not sure if this is against the intended design, but if you're looking for something like ChangeNotifier but decoupled from Flutter, you can accomplish something like it as so:

abstract class StateChangeNotifier extends StateNotifier<void> {
  StateChangeNotifier() : super(null);
  void notifyListeners() => state = null;
}

I wouldn't recommend this is in many cases because StateNotifier forces you to separate the state into its own object which ends up with cleaner code.