我看过 google io19 的 Pragmatic state management 视频,关于 package:provider/provider.dart
它管理状态的方法。它看起来很简单,但我对在类的方法中访问状态有疑问。
在课堂上说我需要更新状态:
_onTap(data) {
appState.data = data;
}
在类的构建方法中,我得到了状态:
this._appState = Provider.of<AppState>(context);
现在我需要二传手,所以我在做:
set _appState(newValue) {
appState = newValue;
}
最后,我需要在课堂上使用 state 字段:
class Tapable extends StatelessWidget {
var appState;
_onTap(data) {
appState.data = data;
}
set _appState(newValue) {
appState = newValue;
}
@override
Widget build(BuildContext context) {
this._appState = Provider.of<AppState>(context);
return SomeWidget(
onTap: () { _onTap(data) }
)
}
}
令人惊讶的是它有效,但这段代码对我来说很臭,所以我怀疑这是正确的方法。
谢谢。