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

Question

Asked by Toujo on January 10, 2022 (source).

I have dropdown in my app. It's working fine, but whenever i'm selecting an item from drop down its reload the whole page and set the value. Why so? can't I set the value in my variable without reloading my screen using setState(){}?

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

then using this dropdown under my 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!;
                });
               },
             ),

image

Answer

Question answered by FlutterChicken (source).

According to the 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.

So if the state of the widget changes you have to call setState to trigger a rebuild of the view and see immediately the changes implied by the new state.

Video Answers on YouTube

DART FLUTTER STATE-MANAGEMENT
SHARE: