首页 > 解决方案 > 在 Flutter 输入中将值转换为数字格式?

问题描述

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

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

例如,如果我输入:

等等..

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

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

这是我从这篇文章中找到的回复

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

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

有什么办法可以做到这一点?

标签: fluttervalidationdartdecimaltextinput

解决方案


这是巴西的语言环境吗?然后可以在 DecimalTextInputFormatter 类中设置巴西的数字货币格式以达到相同的结果。


推荐阅读