问题描述
你好,我是新手,我正在尝试使用mobx状态管理。
import 'package:mobx/mobx.dart';
part 'counter.g.dart';
class Counter = _Counter with _$Counter;
abstract class _Counter with Store {
@observable
String hello = 'Hello';
@action
void changeName(_name){
hello = _name;
}
}
和.g.dart也会使用更新后的值生成。 我正在触发类似(动作调用部分)的动作
final Counter counter = Counter();
return Observer(builder: (_)=> InkWell(
onTap: () {
counter.changeName("updated value");
}.....something like this.
渲染部分:
final Counter counter = Counter();
return Scaffold(
body: Observer(builder: (_) {
return Container(
height: 100.0,width: 100.0,decoration: Boxdecoration(),child: Text(counter.hello),);
}),
每次我都将counter.hello设为“ Hello”(默认值)。 我没有收到“更新后的价值”
->动作changeName正在触发(我已对其进行调试)
请帮助我。
解决方法
这部分
final Counter counter = Counter();
return Observer(builder: (_)=> InkWell(
onTap: () {
counter.changeName("updated value");
}
和这部分
final Counter counter = Counter();
return Scaffold(
body: Observer(builder: (_) {
return Container(
height: 100.0,width: 100.0,decoration: BoxDecoration(),child: Text(counter.hello),);
}),
是否在同一小部件树中?我注意到在这两个部分中您都实例化了Counter(), 要更新文本,您需要使用该类的相同实例。