我需要在另一个提供者内部使用一个提供者,但我无法做到这一点,我试图使用ChangeNotifierProxyProvider
,但未调用更新功能。
我有2个提供程序,UserProvider和RoleProvider,我需要在UserProvider内部调用RoleProvider或在用登录用户更新UserProvider之后调用RoleProvider。
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');
}
}
答案 0 :(得分:0)
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');
}
}