如何在 Flutter 中正确使用 setState(){}?

How to use setState(){} properly in Flutter?

我的应用程序中有下拉菜单。它工作正常,但每当我从下拉列表中选择一个项目时,它会重新加载整个页面并设置值。为什么这样?我不能在不使用 setState(){} 重新加载屏幕的情况下设置变量中的值吗?

String _selectedHeight = "4 ft";
  List<String> height = ["4 ft", "5 ft", "6 ft", "7 ft"];

然后在我的 FutureBuilder() 下使用这个下拉菜单{}:

        DropdownButton<String>(
          value:_selectedHeight,
          underline:Container(),
          icon: Icon(Icons.keyboard_arrow_down),
          iconSize: 24,
          isExpanded:true,
          items: height.map(( String height) =>DropdownMenuItem<String>(
          child:Text(height),
           value:height,
           )).toList(),
             onChanged:(val) {
                setState(() {
                   _selectedHeight = val!;
                });
               },
             ),

您可以只使用“=”运算符。这会在不刷新状态的情况下更改变量的值。

使用“setstate”是为了refresh/rerender整个组件匹配变化,所以我们不能在不使用setState

重新加载屏幕的情况下设置变量中的值

根据 docs:

Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

因此,如果小部件的状态发生变化,您必须调用 setState 来触发视图的重建并立即查看新状态所暗示的变化。