下拉按钮选择不会在 Flutter 中更新

Dropdown button selection not update in Flutter

我创建了我的下拉按钮,但是无论何时选择一个项目都不会更新value.But每当我热重载时我的所有值都会更新。谁能猜出原因?或者有解决办法吗?

DropdownButton<String>(
                    value: dropdownValue,
                    icon: Icon(Icons.keyboard_arrow_down),
                    iconSize: 15,
                    elevation: 10,
                    style: TextStyle(color: Colors.grey),
                    onChanged: (newValue) {
                      setState(() async {
                        dropdownValue = newValue;
                    final selectedLanguage= await SharedPreferences.getInstance();
                    selectedLanguage.setString('selectedLanguage', dropdownValue);
                      });
                      allTranslations.setNewLanguage(
                        allTranslations.getLocaleKey(
                          dropdownValue,
                        ),
                      );
                    },
                    items: <String>[
                      englishText,
                      chineseText,
                      russianText,
                    ].map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                  ),

@kimSoo 太棒了!

每个人的解决方案是 setstate 中的异步闭包不起作用。我们必须删除它并更早地初始化共享首选项。

早点初始化final selectedLanguage= await SharedPreferences.getInstance();

DropdownButton<String>(
                    value: dropdownValue,
                    icon: Icon(Icons.keyboard_arrow_down),
                    iconSize: 15,
                    elevation: 10,
                    style: TextStyle(color: Colors.grey),
                    onChanged: (newValue) {
                      setState(() { <----- removed async
                        dropdownValue = newValue;
                    
                    selectedLanguage.setString('selectedLanguage', dropdownValue);
                      });
                      allTranslations.setNewLanguage(
                        allTranslations.getLocaleKey(
                          dropdownValue,
                        ),
                      );
                    },
                    items: <String>[
                      englishText,
                      chineseText,
                      russianText,
                    ].map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                  ),