根据文档:
调用setState会通知框架此对象的内部状态已更改,该方式可能会影响此子树中的用户界面,这将导致框架为该State对象安排构建。
因此,如果小部件的状态更改 ,则 必须调用
setState以触发视图重建,并立即查看新状态所隐含的更改。
无论如何,以下片段都是等效的。
第一种情况(直接形式
flutter create <myproject>):
class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); }第二种情况:
class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { _counter++; setState(() {}); }我不知道的原因是,如果第一种情况是常规的使用方式
setState,我会说是因为代码的可读性。



