Flutter:当全局变量随MVVM更改时更新类变量

问题描述

我的应用程序设置方式是让SessionRepository提供程序包装MaterialApp。该存储库使我可以跟踪整个应用程序中有关会话的数据。

  @override
  Widget build(BuildContext context) {
    return Provider<SessionRepository>(
      create: (_) => SessionRepository()),child: MaterialApp(
        ...
      ),);
  }

在我的一个屏幕中,我按照MVVM体系结构创建视图模型,并使用SessionRepository初始化一些视图模型变量。

Widget build(BuildContext context) {
    final session = Provider.of<SessionRepository>(context,listen: false);

    return Provider<Testviewmodel>(
      create: (context) => Testviewmodel(session),child: ...
    );
}

在我的视图模型中,这正在发生:

class Testviewmodel{
  final SessionRepository session;
  final var foo;
  final var bar;

  Testviewmodel(this.session) : foo = session.foo,bar = session.bar;
}

我的问题是,每当更新会话变量时,我也希望视图模型存储更新后的变量。我想不出有什么办法可以在更新会话,输入任何内容自动完成?

解决方法

如果要通知视图,则SessionRepository属性更改时,并使用新值重新创建视图模型,SessionRepository必须实现ChangeNotifier。查看ChangeNotifierProvider个示例。