AlwaysAtTheEndTextInputFormatter class
AlwaysAtTheEndTextInputFormatter is a TextInputFormatter that forces the cursor to always stay at the end of what is being typed.
Note, just adding AlwaysAtTheEndTextInputFormatter does not prevent text selections, and does not prevent the user to move the cursor using the keyboard arrows. However, if the user types a character when not at the end, the text remains unchanged and the cursor goes to the end of the text.
You can improve this by adding two more changes to your code:
-
Add
enableInteractiveSelection: falseto the TextField, which will prevent long press selection, copy/paste menu, and selection handles. -
Create a
controllerand add the following code to your widget'sinitState(), which will prevent the cursor from moving horizontally with the keyboard arrows:
final controller = TextEditingController();
bool _fixingSelection = false;
@override
void initState() {
super.initState();
controller.addListener(() {
if (_fixingSelection) return;
final textLength = controller.text.length;
final selection = controller.selection;
if (!selection.isCollapsed || selection.baseOffset != textLength) {
_fixingSelection = true;
controller.selection = TextSelection.collapsed(offset: textLength);
_fixingSelection = false;
}
});
}
Then:
TextField(
controller: controller,
enableInteractiveSelection: false,
inputFormatters: [
AlwaysAtTheEndTextInputFormatter.instance,
],
)
- Inheritance
-
- Object
- TextInputFormatter
- AlwaysAtTheEndTextInputFormatter
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) → TextEditingValue -
Called when text is being typed or cut/copy/pasted in the EditableText.
override
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited