How can i limit textinput lines in flutter
171
Solution 1
Here is the code
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;
}
}
Usage:
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,
),
),
),
Solution 2
Max Lines property is not for that purpose. As per the official documentation, maxlines optional a maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow.
You can use the maxLength property for restrict users to exceed the specified length.
TextFormField(
maxLength: 130,
),
Author by
DW_Cod
Updated on January 05, 2023Comments
-
DW_Cod 5 months
I use TextFormField Widget, and I set the maxlines parameter to 5. But I was able to keep typing. I want to limit input when maxline is reached. what should I do?
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)), ),
-
DW_Cod 11 monthsit works. However, line breaks are not recognized when the user continues to type.