思路:
1、在TextField组件中,用到controller: _textController,属性,用来监听输入内容变化;
2、为_textController编写监听事件,计算输入内容的高度,赋值给整个输入框;
3、用setState()及时更新;
代码实现:
TextEditingController _textController = TextEditingController(); // 用来监听TextField的输入内容
@override
Widget build(BuildContext context) {
/*
* 输入内容变化:监听输入内容变化,(1)动态展示“发送”按钮;(2)动态修改输入框高度
*/
_textController.addListener(() {
var value = _textController.text;
if ( value != null && value != "" && _isShowVoice ) {
_isShowSentButton = true;
} else {
_isShowSentButton = false;
}
_textFieldHeight = _calculateTextFieldHeight(value);
setState(() {});
});
return Column(
children:[
Container(
decoration: const BoxDecoration(color: Color.fromRGBO(241, 243, 244, 0.9)),
child: _buildInputTextComposer(), // 输入框
),
]
);
}
// 输入框组件
Widget _buildInputTextComposer(){
return Container(
height: _textFieldHeight,
child: TextField(
style: const TextStyle(
fontSize: 16
),
controller: _textController,
onSubmitted: _submitMsg,
maxLines: 5 // 最多显示5行
)
)
}
// 计算输入框区域的高度的方法
double _calculateTextFieldHeight(String value){
final textSpan = TextSpan(
text: value,
style: TextStyle(fontSize: 16.0),
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
maxLines: 5, // 最多显示5行
)..layout(maxWidth: MediaQuery.of(context).size.width - 210 ); // 减去/加上的数值根据自己需求调整,下同
return textPainter.height + 24;
}