首页 > 解决方案 > 在 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;
  }

标签: flutterdropdown

解决方案


为了实现这一点,您需要根据当前选定的 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);
}

推荐阅读