问题描述
我在 Flutter 中使用堆叠包 (https://pub.dev/packages?q=stacked) 作为 MVVM 架构。当 viewmodel 更改服务类中的属性时,我需要更新 BaseModel 中的更改。这是我的代码摘要。
class BaseModel extends ChangeNotifier {
final AuthenticationService _authenticationService =
locator<AuthenticationService>();
AppUser get currentUser => _authenticationService.currentUser;
}
class AuthenticationService {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirestoreService _firestoreService = locator<FirestoreService>();
AppUser _currentUser;
AppUser get currentUser => _currentUser;
updateUser(AppUser user) {
_currentUser = user;
}
}
class UserProfileviewmodel extends BaseModel {
final AuthenticationService _authenticationService = locator<AuthenticationService>();
Future updateUser() async{
AppUser user = AppUser(many properties);
await _authenticationService.updateUser(user);
notifyListeners();
}
}
当我调用 UserProfileviewmodel.updateUser() 时,AuthenticationService 中的 _currentUser 更改成功,但是 BaseModel 中的 currentUser 没有同步更新。
我尝试过的: 我尝试过 observable_ish 包,但是,当我在 AuthenticationService 中实现 ReactiveServiceMixin 并将 _currentUser 包装在 RxValue 中时,我无法设置初始值。此外,将 _currentUser 作为参数传递的 AuthenticationService 中的其他函数也会收到错误消息。像这样: 等待 _firestoreService.createuser(_currentUser);
解决方法
您必须在 currentUser
更新 BaseModel
。我不确定让 UserProfileViewModel
继承 BaseModel
的原因。继承类不会传递值。
class BaseModel extends ChangeNotifier {
final AuthenticationService _authenticationService = locator<AuthenticationService>();
AppUser get currentUser => _authenticationService.currentUser;
// Update user
void update(AppUser user) {
_authenticationService.updateUser(user);
notifyListeners();
}
}