输入文本时自动扩展的 Flutter 文本字段,然后在达到特定高度时开始滚动文本

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

我已经尝试了 Flutter TextField 的许多配置,但不知道如何构建这个。

我正在寻找一个最初是单行的文本字段,它会在输入文本时自动扩展,然后在某个时候开始自行滚动。

这可以通过使用 maxLines: null 属性部分实现。但是当输入大量文本时,文本字段中的文本本身会溢出。

如果将 maxLines 设置为一个值,则整个文本字段本身会扩展到那么多行,而不是从一行开始。

有没有办法像 WhatsApp 和 telegram 等许多聊天应用程序那样在某些时候限制文本字段的高度。

Container(
    child: new ConstrainedBox(
        constraints: BoxConstraints(
            maxHeight: 300.0,
        ),
        child: TextField(
                    maxLines: null,
                ),
            ),
        ),
    ),
)

在旧的 Flutter 版本中是

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,
                ),
            ),
        ),
    ),
)

如果您对 TextField 没有任何风格,Gunter 接受的答案就足够了。但是如果 TextField 至少有一个下划线/底部边框,它会在向上滚动时消失。

我的建议是使用 TextPainter 计算行数,然后将计算出的行数应用到 TextField。这是代码,将您当前的 TextField 替换为 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,
      );
    }
  )

现在我们实际上有 TextFieldminLines 参数,不再需要解决方法。

TextField(
    minLines: 1,
    maxLines: 5,
)
TextField(
     minLines: 1,
     maxLines: 5,
     maxLengthEnforced: true,
),