Reputation: 4662
I have a TextFormField
that takes a phone number. I need to maintain the direction of the prefix when I change the language of the app (which changes the direction).
You see in this screenshot that I managed to maintain the text input direction using textDirection: TextDirection.ltr
but the prefix direction still adapts to the RTL layout. Is there a way to keep the prefix in the left position?
TextFormField(
keyboardType: TextInputType.number,
textDirection: TextDirection.ltr,
decoration: InputDecoration(
labelText: 'Phone Number',
labelStyle: const TextStyle(
locale: Locale('en','')
),
prefixText: '🇴🇲 +968 ',
prefixStyle: const TextStyle(
locale: Locale('en',''),
),
helperText: ''),
)
Upvotes: 0
Views: 682
Reputation: 11
Wrap the TextFormField with Directionality
Directionality(
textDirection: TextDirection.ltr,
child: TextFormField(
textInputAction: TextInputAction.done,
maxLines: widget.maxLines ?? 1,
readOnly: widget.readOnly ?? false,
keyboardType: widget.keyboardType,
maxLength: widget.maxLength ?? (widget.isPhone ? 8 : null),
inputFormatters: widget.textInputFormatter,
style: widget.textStyle,.....
Upvotes: 1
Reputation: 96
As the name suggests, a prefix will always be at the beginning of the textfield, so let it be. What we can do here is use a conditional InputDecoration and switch between prefixText and suffixText. This way we don't have to go against the framework and our job will also be done. Suppose we have two languages, English(EN) and Urdu(UR). so our code will be:
String lang = "UR";
TextDirection getTextDirection() {
return lang == "EN" ? TextDirection.ltr : TextDirection.rtl;
}
InputDecoration getInputDecoration() {
if (lang == 'EN')
return InputDecoration(
labelText: 'Phone Number',
labelStyle: TextStyle(locale: Locale('en', '')),
prefixText: '🇴🇲 +968 ',
prefixStyle: const TextStyle(
locale: Locale('en', ''),
),
helperText: '');
else
return InputDecoration(
labelText: 'Phone Number',
labelStyle: TextStyle(locale: Locale('en', '')),
suffixText: '🇴🇲 +968 ',
suffixStyle: const TextStyle(
locale: Locale('en', ''),
),
helperText: '');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body:
TextFormField(
keyboardType:TextInputType.number,
textDirection:getTextDirection(),
decoration:getInputDecoration(),
)
);
}
Upvotes: 2