Introduction to TextField properties
Ideas:
1. In the TextField component, the controller: _textController is used to monitor the input content changes;
2. Write a listening event for _textController, calculate the height of the input content, and assign it to the entire input box;
3. Use setState() to update in time;
Code:
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;
}