如何使用 Flutter 为 DropdownButtonFormField 的选定项目设置右对齐?

How to set right alignment for a selected item of DropdownButtonFormField with Flutter?

我有一个 DropdownButtonFormField 的 Flutter 是这样的:

                  DropdownButtonFormField<String>(
                    decoration: InputDecoration(
                      labelText: "My Label",
                      labelStyle: const TextStyle(fontSize: 20),
                      isDense: true,
                      contentPadding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
                    ),

                    items: ["No", "Yes"].map((label) => DropdownMenuItem(
                      alignment: Alignment.centerRight,
                      child: Text(label),
                      value: label,
                      )).toList(),

                    onChanged: (value) {
                      ....
                    },
                    value: "No",
                    alignment: Alignment.centerRight,
                  ),

生成:

但是 No/Yes 值显示为左对齐。可以显示在右边吗?

我们可以在 DropdownButtonFormField 之上使用 selectedItemBuilder and LayoutBuilder 来欺骗 UI。

 LayoutBuilder(
  builder: (context, constraints) => DropdownButtonFormField<String>(
   //....
    selectedItemBuilder: (c) => ["No", "Yes"]
        .map(
          (e) => SizedBox(
            width: constraints.maxWidth - 24, //-default dropDownIconSize
            child: Text(
              e,
              textAlign: TextAlign.right,
            ),
          ),
        )
        .toList(),
   //....