首页 > 解决方案 > Flutter:添加新号码时TextFiled变得清晰

问题描述

在我的应用程序中,我有一个文本字段。我创建了一个 TextInputFormatter 以添加inputFormatters到我的TextField

class CurrencyTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.isEmpty) {
      return newValue.copyWith(text: '');
    } else if (newValue.text.compareTo(oldValue.text) != 0) {
      var selectionIndexFromTheRight =
          newValue.text.length - newValue.selection.end;
      final f =
          NumberFormat.currency(locale: 'en', decimalDigits: 0, symbol: '');
      var num = int.parse(newValue.text.replaceAll(RegExp('[^0-9]'), ''));
      final newString = f.format(num).trim();
      return TextEditingValue(
        text: newString,
        selection: TextSelection.collapsed(
            offset: newString.length - selectionIndexFromTheRight),
      );
    } else {
      return newValue;
    }
  }
}

一切正常,当我在 TextField 中添加价格时,价格,从右到左分开。

TextField(
  textAlignVertical: TextAlignVertical.center,
  controller: amountController,
  inputFormatters: [
              CurrencyTextInputFormatter(),
              LengthLimitingTextInputFormatter(15),
  ],

在 initState 的 TextField 的父级中,我初始化了文本字段控制器:

  @override
  void initState() {
    super.initState();
    amountController.text =
        commaFormatter.format(widget.provider.totalUnpaidAmount);
  } 

commaFormatter 使用NumberFormatintl 在数字之间添加逗号:

final commaFormatter = NumberFormat("#,###");

问题在这里:

当号码被它的控制器添加到文本字段时,当我想通过软键盘删除键删除这个号码时,这个号码没有被删除?但是当我添加一个新号码时,旧号码完全删除了!!!!

我该如何解决这个问题?

我想在将数字添加到此文本文件时,可编辑

标签: flutterflutter-layout

解决方案


推荐阅读