我已经尝试了许多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,
),
),
),
),
)
现在我们实际上有minLines
参数TextField
,不再需要解决方法。
TextField(
minLines: 1,
maxLines: 5,
)
如果你对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,
);
}
)
TextField(
minLines: 1,
maxLines: 5,
maxLengthEnforced: true,
),