Fran Maric
Fran Maric

Reputation: 73

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!

Upvotes: 3

Views: 1080

Answers (2)

user1111
user1111

Reputation: 2030

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)));

Upvotes: 2

Nirmal Code
Nirmal Code

Reputation: 4068

class UserState {
  UserState({
    required this.id,
    required this.name,
  });

  final int id;
  final String name;
}

class UserNotifier extends StateNotifier<UserState> {
  UserNotifier() : super(UserState(id: 1, name: 'Pero Peric'));
}
  
final userNotifierProvider =
    StateNotifierProvider<UserNotifier, UserState>((ref) => UserNotifier());

In consumer,

final userName =
        watch(userNotifierProvider.select((value) => value.name)); // value is the state

Upvotes: 0

Related Questions