【问题标题】:Flutter - how to update change in all ViewModels when a ViewModel has made a change in a Model's propertyFlutter - 当 ViewModel 对 Model 的属性进行更改时如何更新所有 ViewModel 中的更改
【发布时间】:2021-08-13 08:30:39
【问题描述】:

我在 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 中时,我无法设置初始值。此外,AuthenticationService 中将 _currentUser 作为参数传递的其他函数也会收到错误消息。像这样: 等待_firestoreService.createUser(_currentUser);

【问题讨论】:

    标签: flutter mvvm stacked


    【解决方案1】:

    您必须在BaseModel 上更新currentUser。我不确定让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();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多