I want to make a custom text editing controller which will show the numbers of text in Farsi (Persian), but returns it with English numbers when you call textEditingController.text
.
Here's what I have implemented but it seems like the TextField doesn't use the setter of text
:
class PersianTextEditingController extends TextEditingController {
@override
String get text => value.text.toEnglishNumbers;
@override
set text(String newText) {
value = value.copyWith(
text: newText.toPersianNumbers,
selection: const TextSelection.collapsed(offset: -1),
composing: TextRange.empty,
);
}
factory PersianTextEditingController({String? text}) =>
PersianTextEditingController._(text: text);
PersianTextEditingController._({String? text}) {
this.text = text ?? '';
}
}
Here's the TextField:
PersianTextEditingController controller = PersianTextEditingController();
@override
Widget build(BuildContext context) {
return TextField(
controller: widget.controller,
);
}
CodePudding user response:
try this:
class PersianTextEditingController extends TextEditingController {
@override
String get text => super.value.text.toPersianNumbers;
@override
set text(String persianText) {
super.value = TextEditingValue(
text: persianText.toEnglishNumbers,
selection: TextSelection.collapsed(offset: persianText.length),
);
}
}
and:
TextField(
controller: controller,
onChanged: (value) {
print(controller.text);
},
),
CodePudding user response:
The reason your code doesn't work is that you try to get english number with getter text
, inside the TextEditingController
its use it, so always you are getting english number, you need to set text
to farsi
and define new getter
for english number, like this:
class PersianTextEditingController extends TextEditingController {
@override
String get text => value.text.toPersianNumbers;
String get englishText => value.text.toEnglishNumbers;
factory PersianTextEditingController({String? text}) =>
PersianTextEditingController._(text: text);
PersianTextEditingController._({String? text}) {
this.text = text ?? '';
}
}
but when you want to get your english number use this:
print("text = ${widget.controller.englishText}")