rrousselGit / state_notifier

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

State notifiers that are more idiomatic Flutter #27

Closed scopendo closed 4 years ago

scopendo commented 4 years ago

I've just started using state_notifier with provider (not riverpod). One of the things that I try to do with my notifiers (be they StateNotifier or ValueNotifier) is to make their use similar to the Flutter framework, as I find this easier to read. For example, the way that Theme.of(context) returns a ThemeData object.

Assuming that I have a model class UserData and a state notifier called User (or perhaps CurrentUser), then I add two static methods to the notifier class that are similar to provider's read and watch context extension methods:

class User extends StateNotifier<UserData> {
  User([UserData user]) : super(user);

  /// Get the [User] state notifier without listening.
  static User get(BuildContext context) {
    return context.read();
  }

  /// Returns the [UserData] state of the [User] notifier and listens for updates.
  static UserData of(BuildContext context) {
    return context.watch();
  }

  void someAction() { ... }
}

These methods are then used in the same way as the Provider methods that they encapsulate, but with improved readability, in my opinion.

  @override
  Widget build(BuildContext context) {
    final user = User.of(context);

    return FlatButton(
      child: Text(user.toString()),
      onPressed: () => User.get(context).someAction();
    );
  }

I'm curious whether others agree with this approach and whether there is any possibility to have these methods added automatically – I don't think it's possible with a mixin, I guess it'd have to be code generation and so probably isn't worth the effort.

rrousselGit commented 4 years ago

There is no way to have subclasses inherit static methods. As such, it is impossible to do such a thing automatically.

You could use a code snippet to generate it for your from your IDE