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.
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:
These methods are then used in the same way as the Provider methods that they encapsulate, but with improved readability, in my opinion.
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.