有没有办法始终在DropDownButton中显示提示?

时间:2020-04-02 17:24:54

标签: flutter

例如,可以在TextField中设置带有标签文本的InputDecoration,当没有用户输入时,该文本将显示在TextField的中心,然后在用户输入文本的上方显示。

使用DropDownButton,我似乎只能在用户做出选择之前显示提示文本,然后它消失,仅显示用户的选择。有没有办法模仿TextField的行为?

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用DropDownButtonFormField小部件而不是DropDownButton来实现。 DropDownButtonFormField具有decoration属性,可让您使用labelText,该属性在从列表中选择一个项目后会移至该字段的顶部。下面的示例工作代码:

return DropdownButtonFormField<String>(
      decoration: InputDecoration(
        labelText: 'select option'
      ),

      value: selected,
      items: ["A", "B", "C"]
          .map((label) => DropdownMenuItem(
                child: Text(label),
                value: label,
              ))
          .toList(),
      onChanged: (value) {
        setState(() => selected = value);
      },
    );

输出:

enter image description here

enter image description here

希望这能回答您的问题。