gpt4 book ai didi

Flutter 多线与最大线数

转载 作者:行者123 更新时间:2023-12-05 08:31:15 25 4
gpt4 key购买 nike

我正在使用具有这些属性的文本字段:

 TextField(
controller: textController,
keyboardType: TextInputType.multiline,
maxLines: 4,
maxLength: 150,
),

这很好用,但我想知道如何防止用户输入换行符,这会导致文本字段的行数超过 maxLines (4)..

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

输入 1\n\n\n 应该有效

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

最佳答案

我修改了 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;
}
}

用法:

TextField(
decoration: InputDecoration(),
maxLines: 4,
inputFormatters: [MaxLinesTextInputFormatter(4)],
)

关于Flutter 多线与最大线数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59427590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com