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

后端 未结 4 1867
后悔当初
后悔当初 2020-12-14 03:36

I\'ve tried many configurations of the Flutter TextField but can\'t figure out how to build this one.

I\'m looking for a textfield that is a single line initially an

4条回答
  •  春和景丽
    2020-12-14 04:26

    The accepted answer by Gunter is good enough if you don't have any style for the TextField. But if you have at least an underline / bottom border for the TextField, it will disappear when scroll up.

    My recommendation is to calculating the lines with TextPainter, then apply the calculated number of lines to TextField. Here's the code, replace your current TextField with 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,
          );
        }
      )
    

提交回复
热议问题