自学内容网 自学内容网

Flutter输入框换行后自适应高度

Flutter输入框换行后输入框高度随之增加

效果

请添加图片描述
请添加图片描述

设计思想

通过TextEditingController在build中监听输入框,输入内容后计算输入框高度然后自定义适合的值,并且改变外部容器高度达到自适应高度的目的

参考代码

//以下代码中的值只适用于案例,实际情况还需改为自己需要的实际值

//自定义输入框高度
 double inputH=25; 

 
  Widget build(BuildContext context) {
    _textEditingController.addListener(() {
      String textvalue=_textEditingController.text;
      final textStyle = TextStyle(fontSize: 16,fontWeight: FontWeight.bold);

      final textPainter = TextPainter(
        text: TextSpan(text:textvalue, style: textStyle),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout(maxWidth: 260 * Global.widthX); // 减去/加上的数值根据自己需求调整,下同
      setState(() {
        if(textPainter.height<=25.0){ //只有一行的情况
          this.inputH=25.0;
        }else if(25.0<textPainter.height && textPainter.height<=95){ //大于一行小于等于4行的情况
          this.inputH=textPainter.height;
        }else if(textPainter.height>=95){ //大于四行后固定高度,输入框内容滑动展示
          this.inputH=95.0;
        }
      });
     
    });
return Container();

}

Widget _bottom(){
 return SizedBox(
height:inputH*Global.heightY+80*Global.heightY,
child:Container(
//输入框外部容器高度
 constraints: BoxConstraints.tightFor(width: Global.screenWidth,height:inputH*Global.heightY+50*Global.heightY),
 child: Container(
            constraints: BoxConstraints(
                maxHeight: 100.0,
                maxWidth: 265 * Global.widthX,
                minHeight: 20*Global.heightY,
                minWidth: 265 * Global.widthX),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(  //边框,颜色以及宽度
                // color: Color(0xFFFCCCCCC),
                width: 1.0,
                color: Colors.black12
              ),
              borderRadius: BorderRadius.circular(10.0),
            ),
            margin: EdgeInsets.fromLTRB(9* Global.widthX, 0, 0, 0),
            padding: EdgeInsets.fromLTRB(5* Global.widthX,0, 0, 0),
            child: Center(

              child: TextField(
                // focusNode: _focusNode1,
                maxLines: null,
                // maxLength: 170,
                keyboardType: TextInputType.multiline,
                controller: _textEditingController,
                // textAlign: TextAlign.center,
                textAlignVertical: TextAlignVertical.center,
                decoration: InputDecoration.collapsed(

                  hintText: _hintText,

                ),
                
              ),
            ),
          ),
 
)
);
}

原文地址:https://blog.csdn.net/weixin_43626889/article/details/136348027

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!