[英]Flutter not updating DropdownButton placed within a dialog when item is selected
[英]Flutter dropdownButton setState on change not updating dropdown text after selection to show selected item
我創建了一個下拉按鈕,允許用戶從下拉列表中選擇 select,該下拉列表將從 API 填充。 現在我正在使用我創建的列表進行填充。
目前,該按鈕正在顯示我列表中的項目,但在進行選擇后,列表不顯示所選項目,但仍顯示提示文本。 我想要發生的是在做出選擇之后,然后 dropdownButton 顯示被選擇的項目而不是提示文本。
在 onChanged 方法中,我添加了一個 setState,希望將 _selectedValue 變量更新為所選值並將其顯示在下拉按鈕中。
我還在我的 setState 方法中添加了一個 print 語句,它會觸發並向我顯示 value 變量中的值。
這是我的代碼。
List<DropdownMenuItem<int>> listItems = [DropdownMenuItem(child: Text("2016"), value: 2016,), DropdownMenuItem(child: Text("2021"), value: 2021,)];
int _selectedValue;
body: DropdownButton(
value: _selectedValue,
items: listItems,
hint: Text("Select Year"),
onChanged: (int value){
setState(() {
_selectedValue = value;
print(value);
});
},
),
您的代碼很好,但問題可能是您正在初始化 build() 方法中的_selectedValue
。 因此,每當您調用 set state 時,小部件都會重建並使用默認值再次初始化。
int _selectedValue;
@override
Widget build(BuildContext context) {
return DropdownButton(
value: _selectedValue,
items: listItems,
hint: Text("Select Year"),
onChanged: (int value){
setState(() {
_selectedValue = value;
print(value);
});
},
),
萬一其他人遇到這個問題,我也遇到了同樣的問題,這讓我發瘋了,我正在適當地使用 setState() 等等,我在 100% 的地方定義了“initialValue”屬性。
我在構建方法中定義它。 這不起作用,即使我在姊妹模塊中有相同的設置並且確實有效。 不知道為什么會這樣。
一旦我將該變量的定義更改為 state class,它就像一個魅力。 希望它能節省一些,一些周期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.