setState为什么要关闭? [英] Why does setState take a closure?

查看:71
本文介绍了setState为什么要关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有 setState()有什么好处 接受一个函数只是立即调用它,然后请求重建吗?特别是,与让用户显式调用重建类型的函数相比,有什么好处?

What's the benefit of having setState() accept a function just to immediately call it and then request rebuild? In particular, what's the advantage over having users explicitly call a "rebuild" type function?

推荐答案

当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.

如果您遵循只对<$内的成员变量进行变异的约定, c $ c> 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 rel = noreferrer> State ,因此发生在 initState setState 回调将被标记为可疑。

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小部件浏览。我发现使用setState 的情况。 widgets / FutureBuilder-class.html rel = noreferrer> FutureBuilder StreamBuilder AnimatedWidget AnimatedBuilder ,因此,如果您发现自己呼叫<$,请不要忘记考虑这些替代方法

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对此问题/答案做出了贡献。

这篇关于setState为什么要关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆