0

我看过 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) }
    )
  }
}

令人惊讶的是它有效,但这段代码对我来说很臭,所以我怀疑这是正确的方法。

谢谢。

4

1 回答 1

0

If you have state, such that changing state should update your widget, you should use a StatefulWidget, and use setState() to trigger the rebuild. StatelessWidget is for widgets that are essentially "view only".

于 2019-06-11T02:20:28.337 回答