Flutter textfield that auto expands when text is entered and then starts scrolling the text when a certain height is reached

被刻印的时光 ゝ 提交于 2019-11-30 04:03:31
Container(
    child: new ConstrainedBox(
        constraints: BoxConstraints(
            maxHeight: 300.0,
        ),
        child: new Scrollbar(
            child: new SingleChildScrollView(
                scrollDirection: Axis.vertical,
                reverse: true,
                child: new TextField(
                    maxLines: null,
                ),
            ),
        ),
    ),
)

The accepted answer by Gunter is good enough if you don't have any style for the TextField. But if you have at least an underline / bottom border for the TextField, it will disappear when scroll up.

My recommendation is to calculating the lines with TextPainter, then apply the calculated number of lines to TextField. Here's the code, replace your current TextField with LayoutBuilder :

LayoutBuilder(
    builder: (context, size){
      TextSpan text = new TextSpan(
        text: yourTextController.text,
        style: yourTextStyle,
      );

      TextPainter tp = new TextPainter(
          text: text,
          textDirection: TextDirection.ltr,
          textAlign: TextAlign.left,
      );
      tp.layout(maxWidth: size.maxWidth);

      int lines = (tp.size.height / tp.preferredLineHeight).ceil();
      int maxLines = 10;

      return TextField(
        controller: yourTextController,
        maxLines: lines < maxLines ? null : maxLines,
        style: yourTextStyle,
      );
    }
  )

Now we actually have minLines parameter of TextField, no workaround needed anymore.

TextField(
    minLines: 1,
    maxLines: 5,
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!