我使用 TextFormField Widget,并將 maxlines 引數設定為 5。但我能夠繼續輸入。我想在達到 maxline 時限制輸入。我應該怎么辦?
TextFormField(
controller: _contextController,
cursorColor: Colors.white,
textAlign: TextAlign.center,
focusNode: _contextFocus,
keyboardType: TextInputType.multiline,
minLines: 1,
maxLines: 5,
inputFormatters: [F],
decoration: InputDecoration(
fillColor: Color(0xBD000000),
filled: true,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
border: InputBorder.none,
errorBorder: InputBorder.none,
contentPadding: EdgeInsets.all(20),
hintText: _contextHint,
hintStyle: TextStyle(color: Colors.white)),
),
uj5u.com熱心網友回復:
Max Lines 屬性不用于此目的。根據官方檔案, maxlines 可選文本跨越的最大行數,必要時換行。如果文本超過給定的行數,將根據溢位截斷。
您可以使用 maxLength 屬性來限制用戶超過指定的長度。
TextFormField(
maxLength: 130,
),
uj5u.com熱心網友回復:
這是代碼
class MaxLinesInputFormatters extends TextInputFormatter {
MaxLinesInputFormatters(this.maxLines)
: assert(maxLines == null || maxLines == -1 || maxLines > 0);
final int maxLines;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
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;
}
}
用法:
TextFormField(
cursorColor: Colors.white,
textAlign: TextAlign.center,
focusNode: _contextFocus,
keyboardType: TextInputType.multiline,
minLines: 1,
maxLines: 5,
inputFormatters: [MaxLinesInputFormatters(5)],
decoration: InputDecoration(
fillColor: Color(0xBD000000),
filled: true,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
border: InputBorder.none,
errorBorder: InputBorder.none,
contentPadding: EdgeInsets.all(20),
hintText: _contextHint,
hintStyle: TextStyle(
color: Colors.white,
),
),
),
uj5u.com熱心網友回復:
maxLines 限制 TextField 的高度,而不是內容的長度。maxLength 確實限制了內容的長度,但限制了字符數,而不是行數。這里添加了類似的問題:How to limit the number of inputable lines in a textField
uj5u.com熱心網友回復:
你不能通過行來限制它,你必須像這樣通過字數的長度來限制用戶。
inputFormatter: [
LengthLimitingTextInputFormatter(10),
],
用你的字數替換 10。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/497938.html
