提问人: 提问时间:10/9/2019 最后编辑:Madara's Ghost 更新时间:10/15/2019 访问量:4097
在 Flutter 的另一个 DropdownButton 中选择选项时,禁用 DropdownButton 中的选项
Disable option in DropdownButton when selecting an option in another DropdownButton in Flutter
问:
我正在使用 flutter 创建一个移动应用程序(使用 Android Studio)。我有以下要求:我需要三个具有相同项目列表的 Dropdown-Menus(flutter 中的 DropdownButton)。在其中一个下拉列表中选择某个项目时,它应该在其他两个下拉列表中被禁用(无法再选择)。
这怎么能做到呢?我对 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;
}
答:
2赞
Pablo Barrera
10/9/2019
#1
为了实现这一点,你需要根据当前选定的 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 点击手势并选择该选项
这将是知道是否应该禁用选项的条件
bool isDisabled(int index, String value) {
return dropDowns[index] != value && dropDowns.contains(value);
}
评论