【问题标题】:Flutter money text formatting with TextFormField使用 TextFormField 颤振金钱文本格式
【发布时间】:2020-04-05 08:45:21
【问题描述】:

我创建了一个用于输入任何金额(货币)的小部件。输入金额时,应自动格式化,例如10000 should be 10,000。对于格式化,作为货币的文本我使用了一个名为 flutter_money_formatter 的包。这个包装可以完美地工作,但是当我使用它来为 TextFormField 格式化文本时,它不会产生正确的结果,如您在所附图像中看到的那样。

以下代码用于文本字段小部件。

在这里,我正在使用控制器格式化输入更改方法中的值(我想这不是最好的方法)。我认为问题出在那儿。

import 'package:bright_group_tuition/helpers/Utility.dart';
import 'package:flutter/material.dart';
import '../helpers/Validators.dart';

class RoundedMoneyTextFormField extends StatefulWidget {
  final String label;
  final Function onInput;
  final value;
  final Function onTap;
  final readOnly;

  RoundedMoneyTextFormField(
      {@required this.label,
      this.onInput,
      this.value,
      this.onTap,
      this.readOnly = false});

  @override
  _RoundedMoenyTextFromFieldState createState() =>
      _RoundedMoenyTextFromFieldState();
}

class _RoundedMoenyTextFromFieldState extends State<RoundedMoneyTextFormField> {
  final TextEditingController controller = TextEditingController();
  String storedValue;

  @override
  void initState() {
    controller.text = widget.value;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    storedValue = widget.value.toString();

    return Padding(
      padding: const EdgeInsets.only(top: 15),
      child: TextFormField(
        readOnly: widget.readOnly,
        controller: controller,
        onChanged: (String val) {
          widget.onInput(val);
          setState(() {
            controller.text = Utility.formatCurrency(val, withOutDecimal: true);
            controller.selection = TextSelection.fromPosition(
                TextPosition(offset: controller.text.length));
          });
        },
        onTap: widget.onTap,
        validator: (String val){
          if(val.isEmpty) {
            return 'This field is required';
          }

          if(!isNumeric(Utility.cleanCurrencyFormat(val))) {
            return 'Invalid number';
          }
          return null;
        },
        keyboardType: TextInputType.numberWithOptions(),
        maxLines: null,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(10.0),
            ),
          ),
          filled: true,
          hintStyle: TextStyle(color: Colors.grey[800]),
          labelText: this.widget.label,
          fillColor: Colors.white70,
          alignLabelWithHint: true,
          isDense: true,
        ),
      ),
    );
  }
}

以下代码用于将文本格式化为货币。 除了我创建的文本字段之外,此代码在任何地方都可以正常工作。

static String formatCurrency(String amount,
      {bool withSymbol = false, bool withOutDecimal = false}) {
    FlutterMoneyFormatter fmf = FlutterMoneyFormatter(
      amount: double.tryParse(amount),
      settings: MoneyFormatterSettings(
        symbol: '₹',
        thousandSeparator: ',',
        decimalSeparator: '.',
        symbolAndNumberSeparator: ' ',
        fractionDigits: 2,
      ),
    );

    if (withSymbol) {
      return fmf.output.symbolOnLeft;
    }

    if (withOutDecimal) {
      return fmf.output.withoutFractionDigits;
    }

    return fmf.output.nonSymbol;
  }

任何帮助将不胜感激......

【问题讨论】:

    标签: android flutter formatting flutter-dependencies


    【解决方案1】:

    由于flutter_money_formatter是很久以前更新的,您可以考虑使用currency_text_input_formatter,它还支持空安全语言功能。

    这是一个示例,除了来自软件包文档:

    import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      final CurrencyTextInputFormatter _formatter = CurrencyTextInputFormatter();
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Welcome to Flutter',
          home: Scaffold(
            appBar: AppBar(
              title: Text('Welcome to Flutter'),
            ),
            body: Center(
              child: Column(
                children: [
                  TextField(
                    inputFormatters: [CurrencyTextInputFormatter()],
                    keyboardType: TextInputType.number,
                  ),
                  TextFormField(
                    initialValue: _formatter.format('000'),
                    inputFormatters: <TextInputFormatter>[_formatter],
                    keyboardType: TextInputType.number,
                  ),
                  TextField(
                    inputFormatters: <TextInputFormatter>[
                      CurrencyTextInputFormatter(
                        // locale: 'ko',
                        decimalDigits: 0,
                        symbol: 'USD',
                      ),
                    ],
                    keyboardType: TextInputType.number,
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多