flutter - 在 Flutter 中选择另一个 DropdownButton 中的选项时禁用 DropdownButton 中的选项
问题描述
我正在用颤振创建一个移动应用程序(使用 Android Studio)。我有以下要求:我需要三个具有相同项目列表的下拉菜单(颤振中的下拉按钮)。当在其中一个下拉列表中选择一个项目时,它应该在其他两个下拉列表中被禁用(不能再被选择)。
怎么可能呢?我对颤动相当陌生,但我曾经使用 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 轻击手势将触发并选择该选项
这将是知道是否应该禁用选项的条件
bool isDisabled(int index, String value) {
return dropDowns[index] != value && dropDowns.contains(value);
}
推荐阅读
- javascript - 打字稿错误在类型上找不到带有“字符串”类型参数的索引签名
- reactjs - 用于电容器存储的定制挂钩
- c++ - 错误:未在此范围内声明“res_ninit”;你的意思是“res_init”吗?
- css - Stylus:如何使用 Mixin 插值创建 CSS 变量
- c# - Selenium - 开始你的普通铬而不是铬
- python-3.x - 为什么 Pandas ExcelWriter 会截断数据框的单元格内容?
- c# - .NET Core Quartz 异常重试作业
- azure - 加载在管道最后一次成功运行的开始时间到 sysdate 之间发布的所有文件
- javascript - 保留最后一个值
- javascript - 如何编辑字符串中可能的电话号码?