在Flutter中选择另一个DropdownButton中的选项时,禁用DropdownButton中的选项

时间:2019-10-09 11:46:50

标签: flutter dropdown

我正在使用Flutter(使用Android Studio)创建一个移动应用。我有以下要求:我需要具有相同项目列表的三个Dropdown-Menus(在Flutter中为DropdownButton)。如果在其中一个下拉菜单中选择了一项,则应该在其他两个下拉菜单中将其禁用(无法再选择)。

那怎么办?我不太熟悉,但是曾经使用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;
  }

1 个答案:

答案 0 :(得分:3)

要实现此目的,您需要具有根据当前选定的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);
}