Flutter -制作自定义文本编辑控制器

2mbi3lxu  于 2022-11-17  发布在  Flutter
关注(0)|答案(2)|浏览(255)

我想做一个自定义的文本编辑控制器,它将显示波斯语(波斯语)的文本数字,但当你调用textEditingController.text时,它返回的是英语数字。
下面是我实现的内容,但似乎TextField不使用text的setter:

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 ?? '';
  }

}

下面是文本字段:

PersianTextEditingController controller = PersianTextEditingController();
@override
    Widget build(BuildContext context) {
        return TextField(
          controller: widget.controller,
        );
      }
fnvucqvd

fnvucqvd1#

你的代码不工作的原因是你试图用getter text获取英语数字,在TextEditingController中使用它,所以你总是得到英语数字,你需要将text设置为farsi并为英语数字定义新的getter,如下所示:

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 ?? '';
  }
}

但是当你想得到你的英语号码时,使用这个:

print("text = ${widget.controller.englishText}")
fcipmucu

fcipmucu2#

试试这个:

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),
    );
  }
}

以及:

TextField(
      controller: controller,
      onChanged: (value) {
        print(controller.text);
    
      },
    ),

相关问题