Flutter 如何观察Mobx颤振中其他类的场变量?

Flutter 如何观察Mobx颤振中其他类的场变量?,flutter,dart,mobx,Flutter,Dart,Mobx,我使用flutter Mobx进行状态管理。 我有一个简单的课程:- class A { int x; A(this.x); } 如何观察另一个Mobx存储中的类内是否发生了x更改:- class MyStore extends _MyStore with _$MyStore { Subs(A a) : super(a); } abstract class _MyStore with Store { @observable A a; _Subs(this.a)

我使用flutter Mobx进行状态管理。 我有一个简单的课程:-

class A {
  int x;
  A(this.x);
 }
如何观察另一个Mobx存储中的类内是否发生了
x
更改:-

class MyStore extends _MyStore  with _$MyStore  {
  Subs(A a) : super(a);
}

abstract class _MyStore  with Store {
  @observable
  A a;
  _Subs(this.a)
}
我想
MyStore
观察a.x


有可能吗,如果有,怎么做?

我不确定这是否有帮助,因为它是Javascript/Typescript,但我会这么做:

class Foo {
  @observable name = 'foo'
}

class Bar {
  foo: Foo

  constructor(instanceOfFoo) {
    this.foo = instanceOfFoo

    autorun(() => {
      // Logs foo name when it changes
      console.log(this.foo.name)
    })

    reaction(
      () => this.foo.name,
      () => {
        // Logs foo name when it changes
        console.log(this.foo.name)
      }
    )
  }

  @observable
  name = 'bar'

  @computed
  get fooNamePlusBarName {
    // recomputes automatically whenever foo or bar name changes
    return this.foo.name + this.name
  }
}

基本上,您将
Foo
实例传递给
Bar
构造函数(或者只要使用导入的singleton,如果它适合您),然后您就有3个选项:
computed
reaction
autorun
我前几天使用flift
mobx^1.2.1+3
(dart)和
flatter\u mobx^1.1.0+2

我想到的第一件事是用
@observable
属性注释有问题的字段,即
x
。但在商店之外,它似乎并不有效。 所以你必须使用可观察类来观察这个场

要使其正常工作,您的代码应该如下所示:

class A {
  //replace with less verbose "var"
  Observable<int> x = Observable(0);
  A(this.x);
 }

class MyStore extends _MyStore  with _$MyStore  {
  Subs(A a) : super(a);
}

abstract class _MyStore  with Store {
  
  A a;
  _Subs(this.a)
  
  //Will be calculated whenever a change to a.x is observed.
  @computed
  int get xSquare => a.x.value * a.x.value;
}

A类{
//替换为不太详细的“var”
可观测x=可观测(0);
A(本条第x款);
}
类MyStore使用$MyStore扩展了MyStore{
潜艇(A):超级(A);;
}
抽象类_mystorewith Store{
A A;
_潜艇(本章a节)
//将在观察到a.x的变化时进行计算。
@计算
int get xSquare=>a.x.value*a.x.value;
}
如您所见,我从
a
中删除了可观察属性,因为如果您想对存储中
a.x
的更改做出反应,则不需要观察该属性。您可能注意到您必须使用
.value
访问可观察值

这应该说明您是如何观察商店外部、商店内部的类字段的