【发布时间】:2021-12-12 04:08:22
【问题描述】:
我已经没有想法了。
我正在使用 Mobx 进行非常简单的状态管理。
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:jw_helper/state/globalState.dart';
class Router extends StatelessWidget {
const Router({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final _globalState = GlobalState();
return Column(
children: <Widget>[
Container(
child: Observer(
builder: (_) => Text(_globalState?.currentIndex?.toString()),
),
),
MaterialButton(
onPressed: () {
_globalState.setCurrentIndex(1);
},
child: Text("Press me"),
),
],
);
}
}
当我改变这个小部件中的状态时,值会更新。 当我在另一个 Widget 中改变相同的 Observable 时,Observer 不会重建。
仅更新状态发生突变的同一 Widget 中的观察者。
我的 Mobx 代码:
import 'package:mobx/mobx.dart';
// Include generated file
part 'globalState.g.dart';
// This is the class used by rest of your codebase
class GlobalState = _GlobalState with _$GlobalState;
// The store-class
abstract class _GlobalState with Store {
@observable
int currentIndex = 0;
@action
void setCurrentIndex(index) {
currentIndex = index;
print(currentIndex);
}
}
小提示:打印语句总是被触发
也许有人知道如何解决这个问题。 谢谢;)
【问题讨论】: