如何在 DropdownButton 中居中文本?

Raj*_*eep 9 dart flutter flutter-layout

我试图让DropdownButton提示、文本和菜单项出现在中心而不是左边,但TextAlign.center似乎没有做任何事情。

带有提示的下拉图像:

在此处输入图片说明

带有所选项目的下拉列表图像作为文本:

在此处输入图片说明

按下箭头时菜单项的图像:

在此处输入图片说明

我的代码:

return Theme(
  data: ThemeData(canvasColor: blackTrans2, brightness: Brightness.dark),
  child:Container(
    width: MediaQuery.of(context).size.width/1.2,
    decoration: BoxDecoration(
    color: blackTrans,
    borderRadius: BorderRadius.all(Radius.circular(5.0)),
    ),   
    child:DropdownButtonHideUnderline(
      child: ButtonTheme(
        alignedDropdown: true,
        child: DropdownButton(
          value: _dateSelected,
          hint: AutoSizeText(NA_FLIGHT_PAGE_DROPDOWN, style: TextStyle(color: white,),textAlign: TextAlign.center,),
          isDense: false,
          onChanged: (String newValue){
            setState(() {
            _dateSelected = newValue;
            });
          },
          items: snapshot.data.documents.map((DocumentSnapshot document){
            return DropdownMenuItem<String>(
              value: document.documentID,
              child: AutoSizeText(document.documentID, style: TextStyle(color: white,),textAlign: TextAlign.center,),
            );
          }).toList(),
        ),
      ),
    )
  )
);
Run Code Online (Sandbox Code Playgroud)

不确定这是否会影响任何事情,但我正在使用AutoSizeText来动态调整文本大小。

更新:我设法通过使用使菜单项出现在中心Center,但即使使用Center... ,文本和提示仍然保留在左侧:

// Does not seem to change the hint or text position (when menu item selected)
hint: Center(child:AutoSizeText(NA_FLIGHT_PAGE_DROPDOWN, style: TextStyle(color: white,),textAlign: TextAlign.center,)),

// Changes the menu item to the center instead of left
child: Center(child:AutoSizeText(document.documentID, style: TextStyle(color: white,),textAlign: TextAlign.center,)),
Run Code Online (Sandbox Code Playgroud)

Jun*_*dhi 11

对于那些看到更改颤振类dropdown.dart 选项的人。你不需要这样做。做这个:

  1. 设置属性isExpandedtrue
  2. Center小部件与DropdownMenuItem类子项一起使用。

IsExpanded 也会处理溢出。

DropdownButton(
     isExpanded: true,
     value: category_selected,
     items: categories.map<DropdownMenuItem<String>>((var value) {
        return DropdownMenuItem<String>(
          value: value["name"],
          child: Center(
                 child: Text(
                        value["name"],
                        textAlign: TextAlign.center,
                      ),
                    ),
                 );
           }).toList(),
      ),
Run Code Online (Sandbox Code Playgroud)


小智 3

一个简单而直接的答案是“不可能”。但总有办法的。

您必须转到 flutter 包提供的 dropdown.dart。如果您Ctrl+ClickDrpoDownMenuItem类上使用 VSCode 并更改以下代码。

@override
  Widget build(BuildContext context) {
    return Container(
      height: _kMenuItemHeight,
      alignment: AlignmentDirectional.centerStart,
      child: child,
    );
  }
Run Code Online (Sandbox Code Playgroud)

更改为alignment: AlignmentDirectional.centerStartalignment: AlignmentDirectional.center它应该可以工作:)