I have a class called NavigatorRepository
that I am trying to access, userProvider
. How should I be accessing the userProvider inside the NavigatorRepository
? I feel like i’ve tried everything, except the right thing…
Here is a snippet from NavigatorRepository
final user = Provider((ref) {
return ref.watch(userProvider.notifier).getUser();
});
...
class NavigatorRepository {
...
Future<dynamic> _get(
String path, {
Map<String, Object?>? queryParameters,
}) async {
var x = user; <== How do I get this to work?
}
}
UserProvider
class UserNotifier extends StateNotifier<User> {
UserNotifier()
: super(User(accessToken: '');
void setUser(User user) {
state = user;
}
User getUser() {
return state;
}
}
final userProvider = StateNotifierProvider<UserNotifier, User>((ref) {
return UserNotifier();
});
2
Answers
Found this thread which covers what I am trying to do.
https://github.com/rrousselGit/riverpod/issues/295#issuecomment-770384596
There are many ways to do this.
ref
parameter to the class constructor:The idea is that you pass all necessary dependencies immediately to the constructor of your class. In the end, you know for sure that your class-service only depends on the services that are in the constructor.
Note also that I have made all services private to avoid outside access. If you don’t need it, make the fields open.
ref
parameter when calling any method:Although here you could pass
User user
as a parameter to the method and use it inside. But apparently there can be more such dependencies and then it is easier just to passref
.