Flutter - 当 ViewModel 对模型的属性进行更改时如何更新所有 ViewModel 中的更改

问题描述

我在 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();
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...