I have a textfield in flutter as follows:
Widget build(BuildContext context) {
return TextField(
maxLines: null,
onChanged: (value) {
print(value);
},
autofocus: false,
controller: smcontroller,
textDirection: TextDirection.rtl,
textAlignVertical: TextAlignVertical.center,
style: const TextStyle(
color: Color(0xffffffff),
),
decoration: InputDecoration(
hintText: AppLocalizations.translate('Type a message'),
hintTextDirection: TextDirection.rtl,
),
);
}
When I type helloš¤© in the textfield, the textfield correctly shows "š¤©hello". But the value on onChanged callback shows "helloš¤©" and the controller also has same value. I want the controller to also have "š¤©hello".
2
Answers
The directionality of the output from the
print
function depends on how you set up the terminal. If you have correctly set up the Flutter widgets to use RTL directionality, whether through theDirectionality
widget or thetextDirection
property ofTextField
, you don’t need to worry about the reversed output from the terminal.The issue you’re encountering with Flutter’s TextField widget is due to the behavior of text direction and how it affects the onChanged callback and the controller’s value. Hereās how you can ensure that both the displayed text and the controller’s value reflect the correct order of characters:
Problem Explanation
Text Direction and Display: Setting TextDirection.rtl correctly displays the text in right-to-left order visually, which is why "š¤©hello" appears correctly as "š¤©hello" in the UI.
Controller and onChanged Callback: The onChanged callback and the controller both reflect the actual text value as entered, without considering the visual order. This is because they store the raw text input without adjusting for display direction.
Solution
To ensure that both the onChanged callback and the controller’s value reflect the displayed order of text ("š¤©hello"), you can manually adjust the text before setting it to the controller. Hereās how you can achieve this: