Reputation: 13724
I need to consume a Provider inside another Provider, but I'm not able to do it, I was trying to use ChangeNotifierProxyProvider
but the update function is not called.
I have 2 providers, UserProvider and RoleProvider, and I need to call RoleProvider inside UserProvider or to call RoleProvider once UserProvider is updated with a logged user.
providers: [
ChangeNotifierProvider(create: (ctx) => UserProvider(),),
ChangeNotifierProxyProvider<UserProvider, RoleProvider>(
create: (_) => RoleProvider(null),
update: (_, userProvider, roleProvider) => RoleProvider(userProvider),
),
],
class UserProvider with ChangeNotifier {
User user;
Future<void> login(String username, String password) async {
this.loginMessage = '';
try {
// Login Process
this.user = new User();
// When there is a new logged user, I need to doSomething in RoleProvider
} catch (e) {
print(e);
this.loginMessage = 'ERROR';
}
notifyListeners();
}
}
class RoleProvider with ChangeNotifier {
final UserProvider userProvider;
List<Student> students;
RoleProvider(this.userProvider) {
print('PARENT PROVIDER CONSTRUCTOR');
}
fetchData() {
print('TEEEEEEEEST');
}
}
Upvotes: 0
Views: 1133
Reputation: 5601
providers: [
ChangeNotifierProvider(create: (ctx) => UserProvider(),),
ChangeNotifierProxyProvider<UserProvider, RoleProvider>(
create: (_) => RoleProvider(),
update: (_, userProvider, roleProvider) => roleprovider.userProvider = userProvider,
// use the roleProvider reference instead of creating a new RoleProvider in the update
),
],
class RoleProvider with ChangeNotifier {
UserProvider userProvider; // No final, if you want to consume one provider inside another
// then just leave it so you can then update its value
List<Student> students;
// No need to use the constructor if you're not going to do anything else besides declare userProvider
fetchData() {
print('TEEEEEEEEST');
}
}
Upvotes: 2