需要解释 Flutter 中的 setState() 函数

Need explanation for setState() function in Flutter

我很困惑为什么我们必须在 setState 中放置一个函数来更新变量。我可以改为更新变量并调用 setState。我修改了 https://flutter.dev/docs/development/ui/widgets-intro

的代码
class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    setState(() {
      _counter++;
    });
  }

相反,我想到了这样做

class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    _counter++;
    setState(() {
    });
  }

这仍然有效,现在我在想为什么让 setState() 有一个函数作为参数,而不是 setState 不能像 setState(); 那样有任何参数,我们会在更新变量后调用它。

在大项目中无法正常运行。所以你的问题的答案是这样的,如果你不使用 setState(() => {});,如果你改变变量的任何值,你的屏幕将无法呈现。所以如果你想在屏幕上改变变量的值时生效,你必须使用 setState(() => {});.

你会在official docs中找到答案:

The provided callback is immediately called synchronously. [...] If you just change the state directly without calling setState, the framework might not schedule a build and the user interface for this subtree might not be updated to reflect the new state.

我认为问题是如果在更改状态后调用setState((){});,UI和状态对象将在短时间内不同步。