具有最大行的颤振多行

ebg*_*g11 1 flutter

我正在使用具有以下属性的文本字段:

 TextField(
    controller: textController,    
    keyboardType: TextInputType.multiline,
    maxLines: 4,
    maxLength: 150,
 ),
Run Code Online (Sandbox Code Playgroud)

哪个工作正常,但我想知道如何防止用户输入中断行,这会导致文本字段的行数超过 maxLines (4)..

有没有办法将线路锁定在 4?例如

输入 1 \n \n \n 应该工作

但 1 \n \n \n \n \n \n 不应该被允许

Cra*_*Cat 6

我修改LengthLimitingTextInputFormatter以获得我自己的MaxLinesTextInputFormatter.

这是代码

class MaxLinesTextInputFormatter extends TextInputFormatter {
  MaxLinesTextInputFormatter(this.maxLines)
      : assert(maxLines == null || maxLines == -1 || maxLines > 0);

  final int maxLines;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue, // unused.
    TextEditingValue newValue,
  ) {
    if (maxLines != null && maxLines > 0) {
      final regEx = RegExp("^.*((\n?.*){0,${maxLines - 1}})");
      String newString = regEx.stringMatch(newValue.text) ?? "";

      final maxLength = newString.length;
      if (newValue.text.runes.length > maxLength) {
        final TextSelection newSelection = newValue.selection.copyWith(
          baseOffset: math.min(newValue.selection.start, maxLength),
          extentOffset: math.min(newValue.selection.end, maxLength),
        );
        final RuneIterator iterator = RuneIterator(newValue.text);
        if (iterator.moveNext())
          for (int count = 0; count < maxLength; ++count)
            if (!iterator.moveNext()) break;
        final String truncated = newValue.text.substring(0, iterator.rawIndex);
        return TextEditingValue(
          text: truncated,
          selection: newSelection,
          composing: TextRange.empty,
        );
      }
      return newValue;
    }
    return newValue;
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

TextField(
  decoration: InputDecoration(),
  maxLines: 4,
  inputFormatters: [MaxLinesTextInputFormatter(4)],
)
Run Code Online (Sandbox Code Playgroud)