Flutter Riverpod: Filter rebuilds with StateNotifier and .select()


This is my current state management solution

class UserState {
    final int id;
    final String name;

class UserNotifier extends StateNotifier<UserState> {
    UserNotifier() : super(User(1, 'Pero Peric'));

final userNotifierProvider = StateNotifierProvider((ref) => UserNotifier());

I want to rebuild my UI only when the name changes not the id!

Riverpod provides a way to do this link but I can’t get it working with my StateNotifier.

I would write it like this but it isn’t working like this.

// inside Consumer widget
final userName = watch(userNotifierProvider.select((value) => value.state.name));

Can you refactor my code to work or propose another solution?

Any help is appreciated!


According to the doc, "this method of listening to an object is currently only supported by useProvider from hooks_riverpod and ProviderContainer.listen".

Try to create another provider, which you can use in UI.

final nameProvider = StateProvider<String>((ref) => ref.watch(userNotifierProvider.select((user) => user.name)));

Answered By – user1111

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *