[英]Disable option in DropdownButton when selecting an option in another DropdownButton in Flutter
我正在使用 flutter(使用 Android Studio)創建一個移動應用程序。 我有以下要求:我需要三個具有相同項目列表的下拉菜單(顫振中的下拉按鈕)。 當在其中一個下拉列表中選擇一個項目時,它應該在其他兩個下拉列表中被禁用(不能再被選擇)。
怎么可能呢? 我對 flutter 相當陌生,但我曾經使用 javascript 做過類似的事情。
到目前為止,這是我的代碼:
List<String> dropDowns = [' -- Wählen Sie ein Fach aus -- ', ' -- Wählen Sie ein Fach aus -- ', ' -- Wählen Sie ein Fach aus -- '];
DropdownButton _createDropDown(var index) {
var dropdownButton = new DropdownButton<String>(
value: dropDowns[index],
icon: Icon(Icons.arrow_downward),
iconSize: 28,
elevation: 16,
style: TextStyle(
color: Colors.deepPurple,
fontSize: 22
),
items: <String>[
' -- Wählen Sie ein Fach aus -- ',
'Bildnerisches Gestalten',
'Deutsch',
'Französisch',
'Englisch',
'Ethik, Religion, Gemeinschaft',
'Italienisch',
'Mathematik',
'Musik',
'Natur und Technik',
'Räume, Zeiten, Gesellschaften',
'Textiles und technisches Gestalten',
'Wirtschaft, Arbeit, Haushalt'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
dropDowns[index] = newValue;
});
}
);
return dropdownButton;
}
為了實現這一點,您需要根據當前選定的 DropdownButtons 啟用或禁用某些內容,而不是將 Text 小部件作為 DropdownMenuItem 的子項:
DropdownMenuItem<String>(
value: value,
child: CustomText(value, isDisabled: isDisabled(index, value)),
)
這將是作為選項顯示的小部件
class CustomText extends StatelessWidget {
final String text;
final bool isDisabled;
CustomText(this.text, {this.isDisabled = false});
@override
Widget build(BuildContext context) {
return GestureDetector(
child: Text(
text,
style: TextStyle(
color: isDisabled
? Theme.of(context).unselectedWidgetColor
: Theme.of(context).textTheme.title.color),
),
onTap: isDisabled ? () {} : null,
);
}
}
請注意,如果禁用該選項,則需要指定一個空的 onTap,否則會觸發 DropdownMenuItem 輕擊手勢和 select 選項
這將是知道是否應該禁用選項的條件
bool isDisabled(int index, String value) {
return dropDowns[index] != value && dropDowns.contains(value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.