【问题标题】:Convert value to number format in Flutter input?在 Flutter 输入中将值转换为数字格式?
【发布时间】:2021-02-14 18:53:26
【问题描述】:

我对 Flutter InputTextField 有疑问。我正在开发一个像 CashApp 这样的应用程序,如果你有一个可以向其他人汇款的功能。

问题是:我需要实现一个数字格式并且只允许两位小数

例如,如果我输入:

  • "1000,25" -> 需要转换为 1.000,25

  • "10000,25" -> 需要转换为 10.000,25

等等..

我一直在使用此代码来达到唯一的两位小数部分

import 'package:flutter/services.dart';
import 'dart:math' as math;

class DecimalTextInputFormatter extends TextInputFormatter {
  DecimalTextInputFormatter({this.decimalRange, this.activatedNegativeValues})
      : assert(decimalRange == null || decimalRange >= 0,
            'DecimalTextInputFormatter declaretion error');

  final int decimalRange;
  final bool activatedNegativeValues;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue, // unused.
    TextEditingValue newValue,
  ) {
    TextSelection newSelection = newValue.selection;
    String truncated = newValue.text;


if (newValue.text.contains(' ')) {
  return oldValue;
}

if (newValue.text.isEmpty) {
  return newValue;
} else if (double.tryParse(newValue.text) == null &&
    !(newValue.text.length == 1 &&
        (activatedNegativeValues == true ||
            activatedNegativeValues == null) &&
        newValue.text == '-')) {
  return oldValue;
}

if (activatedNegativeValues == false &&
    double.tryParse(newValue.text) < 0) {
  return oldValue;
}

if (decimalRange != null) {
  String value = newValue.text;

  if (decimalRange == 0 && value.contains(".")) {
    truncated = oldValue.text;
    newSelection = oldValue.selection;
  }

  if (value.contains(".") &&
      value.substring(value.indexOf(".") + 1).length > decimalRange) {
    truncated = oldValue.text;
    newSelection = oldValue.selection;
  } else if (value == ".") {
    truncated = "0.";

    newSelection = newValue.selection.copyWith(
      baseOffset: math.min(truncated.length, truncated.length + 1),
      extentOffset: math.min(truncated.length, truncated.length + 1),
    );
  }

  return TextEditingValue(
    text: truncated,
    selection: newSelection,
    composing: TextRange.empty,
  );
}
return newValue;
}
}

这是我从post找到的回复

这段代码几乎可以做到这一点。它限制了两位小数部分,但没有 NumberFormat 部分,并且小数部分不使用“逗号”,而是使用“点”。

我想交换 '.'千位,',' 代表小数。并添加 NumberFormat。

有什么方法可以实现吗?

【问题讨论】:

    标签: flutter validation dart decimal textinput


    【解决方案1】:

    这是针对区域设置巴西的吗?然后可以在 DecimalTextInputFormatter 类中设置巴西的数字货币格式以达到相同的结果。

    【讨论】:

    • 不是巴西,而是阿根廷。我可以将语言环境更改为 ARG。我必须在课堂的哪个部分粘贴您的部分?如果不是问题,你能给我一个完整的例子吗?谢谢!
    • 我已将其添加为新类。但我不能输入任何东西,只有一个数字:/。好像卡住了
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2018-10-03
    • 2012-10-06
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多