Flutter - ListView中的DropdownButton溢出

Dah*_*Dah 9 dart flutter

我正在尝试使用Flutter,并且当前正尝试在对话框的列表视图中显示输入字段和下拉列表.但是,我得到的下拉式溢出了视图的水平宽度并导致黄灰色条纹图案(如下所示)

ListView中的DropdownButton小部件溢出

代码是:

    class DataInput extends StatefulWidget {

      @override
      State createState() => new DataInputState("");
    }


    enum DismissDialogAction {
      cancel,
      discard,
      save,
    }

    class DataInputState extends State<DataInput> {
      final String _data;
      static const types = const <Map<String, String>>[
        const {
          "id": "103",
          "desc": "0001 - lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum"
        },
        const {
          "id": "804",
          "desc": "0002 - lorem ipsum lorem ipsum"
        },
      ];

      DataInputState(this._data);

      @override
      Widget build(BuildContext context) {
        final ThemeData theme = Theme.of(context);
        return new Scaffold(
          appBar: new AppBar(
            title: const Text("Details"),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () => Navigator.pop(context, DismissDialogAction.save),
                  child: new Row(
                    children: <Widget>[
                      new Icon(Icons.save, color: Colors.white,),
                      new Text(
                          "Save",
                          style: theme.textTheme.body1.copyWith(
                            color: Colors.white,)
                      )
                    ],
                  )
              ),
            ],
          ),
          body: new ListView(
            shrinkWrap: true,
            children: <Widget>[
              new Text("Set Label"),
              new TextField(
                autocorrect: false,
              ),
              new Text("Select Type"),
              new Container(
                width: new FractionColumnWidth(0.5).value,
                child: new DropdownButton(
                    items: types.map((m) =>
                    new DropdownMenuItem(
                        key: new Key(m["id"]),
                        child: new Text(m["desc"]))
                    ).toList(growable: false),
                    onChanged: null
                ),
              ),
            ],
          ),
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)

错误:

    ??? EXCEPTION CAUGHT BY RENDERING LIBRARY ??????????????????????????????????????????????????????????
    The following message was thrown during layout:
    A horizontal RenderFlex overflowed by 433 pixels.

    The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
    black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
    RenderFlex to fit within the available space instead of being sized to their natural size.
    This is considered an error condition because it indicates that there is content that cannot be
    seen. If the content is legitimately bigger than the available space, consider clipping it with a
    RectClip widget before putting it in the flex, or using a scrollable container rather than a Flex,
    for example using ListView.
    The specific RenderFlex in question is:
    RenderFlex#cc264 relayoutBoundary=up12 OVERFLOWING
    creator: Row ? SizedBox ? DefaultTextStyle ? Stack ? Listener ? _GestureSemantics ?
    RawGestureDetector ? GestureDetector ? DropdownButton ? ConstrainedBox ? Container ?
    RepaintBoundary-[<3>] ? ?
    direction: horizontal
    mainAxisAlignment: space-between
    mainAxisSize: min
    crossAxisAlignment: center
    textDirection: ltr
    verticalDirection: down
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法,但它们不起作用:

  • 将下拉包装在Row,Column,Padding和ClipRect中

有人可以帮助我理解这一点,并说明如何解决它?

更新 使用FittedBox可防止溢出,但文本大小会缩小为不可读.

Raj*_*dav 26

最简单的办法是到添加isExpanded属性trueDropdownButton

例如:

new DropdownButton(
                  isExpanded: true, //Adding this property, does the magic
                  items: [
                    new DropdownMenuItem(
                        child: Text("Some large text that needs to be wrapped or ellipsized", 
                        overflow: TextOverflow.ellipsis),
                    ),
                    new DropdownMenuItem(
                      child: Text("This is another large text that needs to be wrapped or ellipsized", 
                      overflow: TextOverflow.ellipsis),
                    ),
                    new DropdownMenuItem(
                      child: Text("And one more large text that needs to be wrapped or ellipsized", 
                      overflow: TextOverflow.ellipsis),
                    )
                  ],
                  onChanged: (val) {
                    //print(val);
                  }),
Run Code Online (Sandbox Code Playgroud)

  • 传说,我敢说 isExpanded: true 应该是默认值。 (5认同)
  • 如果您不希望所选项目被省略,您还可以将此答案与 DropdownButton 中的“selectedItemBuilder”字段配对。或者,您可以将 itemHeight 指定为 null,以便它可以大于 kMinInteractiveDimension。 (2认同)
  • 设置此参数时,您可能希望将“DropdownButton”包装在“Expanded”小部件中。 (2认同)

Gan*_*pat 14

我设法通过将DropdownMenuItem的子包装在SizedBox中并通过给sizeBox一个固定宽度来解决问题,该宽度不会溢出UI并且看起来仍然很好.

例如.

                   new DropdownMenuItem<String>(
                      value: value,
                      child:  new SizedBox(
                        width: 200.0,
                        child: new Text('Long text with ${value} ')
                      ),
                    )
Run Code Online (Sandbox Code Playgroud)

  • 这很好用。如果您希望能够设置最小和最大宽度而不是固定宽度,您还可以使用 ConstrainedBox 而不是 SizedBox。 (3认同)

bri*_*gan 10

我认为你正在遇到一个合法的错误DropDownButton.这里有一个关于这个问题的Github问题:https://github.com/flutter/flutter/issues/9211

如果您需要立即修复,您实际上可以自己修补DropDownButton!为此:

  1. dropdown.dart从Flutter Framework中打开并将其粘贴到您自己的项目中fixed_dropdown.dart.
  2. DropDownMenuItem从此文件中删除该类,以免与正常的Flutter导入冲突
  3. 重命名DropDownButtonFixedDropDownButton与Flutter导入不冲突
  4. 导航到的build方法_DropdownButtonState.找到IndexedStack里面的Row.IndexedStackExpanded小部件包装.

我在Github问题本身上发布了这个信息,如果你想看到修复程序在行动中,也可以找到这个解决方案的截图!


Vic*_*khe 8

尝试使用 isExpanded: true,

它会自动将文本扩展到新行

DropdownButton(
     isExpanded: true, //Add this property
     items: [
          DropdownMenuItem(
              child: Text("Your Text Here", 
              overflow: TextOverflow.ellipsis),
          ),
}),
Run Code Online (Sandbox Code Playgroud)

参考下图

一行文字没有足够的空间,所以继续下一行

在此处输入图片说明

  • 我投了反对票,因为这个答案已经提供了,用不同的单词写相同的答案是没有意义的。希望你能明白。 (5认同)

小智 7

以上都没有正确解决这个问题。

请尝试此处记录的FittedBox

就像这样包裹你的 DropdownMenuItem 的孩子

DropdownMenuItem<MyDropdownContentClass>(
            child: FittedBox(
              child: Text("dropdown item display"),
              fit: BoxFit.contain,
            ),
          );
Run Code Online (Sandbox Code Playgroud)

它会在绘制期间自动调整整个小部件的大小,即您的 Text()。


Rod*_*vis 6

详细说明 ganapat 答案,您可以通过以下方式设置列表:

final dropdownItems = _list
        .map((String item) => new DropdownMenuItem<String>(
              value: item,
              child: new SizedBox(width: 200.0, child: new Text(item)),
            ))
        .toList();
Run Code Online (Sandbox Code Playgroud)


liv*_*ove 6

如果您正在使用一行,为了使其工作,您必须将行子项设置为Expanded和 DropdownButton isExpanded属性:

Row(
    children: <Widget>[
      Expanded(
        child: DropdownButton<String>(
          isExpanded: true, 
          value: _selectedLanguageNative,
          items: list,
          hint: Text(LanguageLocal.getDisplayLanguage(
              Localizations.localeOf(context).languageCode)["name"]),
          onChanged: (String value) {
            print(value);
            setState(() {
              _selectedLanguageNative = value;
            });
          },
        ),
      ),
    ],
  ),
Run Code Online (Sandbox Code Playgroud)