且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 setState 采用闭包?

更新时间:2023-10-23 22:51:10

当 Flutter 有一个markNeedsBuild"函数时,开发人员最终只是随意调用它.当语法切换到 setState(() { ... }) 时,开发人员更有可能正确使用 API.从机器的角度来看,它们在功能上是等效的,但它们似乎从开发人员那里唤起了不同的代码.

When Flutter had a "markNeedsBuild" function, developers ended up just sort of calling it at random times. When the syntax switched to setState(() { ... }), developers were much more likely to use the API correctly. They are functionally equivalent from the machine's point of view, but they seem to evoke different code from developers.

如果您遵循仅在 setState 闭包内改变成员变量的约定,您将避免重构某些代码并意外删除对 setState的调用的情况>,或不必要地调用 setState.如果你的 State 被卸载了,Flutter 可能会导致断言失败,所以你一开始尝试改变成员,而不是最后,你就会知道出了什么问题.

If you follow the convention of only mutating member variables inside a setState closure, you'll avoid a situation you're refactoring some code and accidentally remove the call to setState, or call setState unnecessarily. And if your State is unmounted, Flutter can fail an assertion so you know something is wrong as soon as you begin trying to mutate members, instead of at the end.

最终可能会有分析器警告强制执行setState 在改变 State,因此任何发生在 initStatesetState 回调之外的成员变量变异都将被标记为可疑.

Eventually there will probably be an analyzer warning enforcing that setState is always called when mutating members of a State, so any member variable mutation that happens outside of initState or a setState callback will be flagged as suspect.

如果您刚刚开始使用 Flutter 中的状态,请查看 Flutter 小部件导览.我发现使用 FutureBuilder, StreamBuilder, AnimatedWidgetAnimatedBuilder,所以如果您发现自己经常调用 setState,请不要忘记考虑这些替代方案.

If you're just getting started with state in Flutter, check out the Flutter widgets tour. I've found that a lot of cases where I was calling setState can be handled more elegantly with FutureBuilder, StreamBuilder, AnimatedWidget, or AnimatedBuilder, so don't forget to consider those alternatives if you find yourself calling setState a lot.

Adam Barth 和 Yaroslav Volovich 对此问题/答案做出了贡献.