51

There's is some way to do a money format in a TextField to when the user going typing the value it going already formatting in real time?

formating while typing.

Like in the above image, while the user is typing the format goes updating the value formatted already.

[UPDATE]

I just found this library that makes it works like a charm: https://pub.dartlang.org/packages/flutter_masked_text

5

12 Answers 12

41

[THIS CODE DOESN'T WORKS FOR ALL CASES]

I just got it working this way, sharing in case someone needs too:

TextField

TextFormField(  
    //validator: ,  
    controller: controllerValor,  
    inputFormatters: [  
        WhitelistingTextInputFormatter.digitsOnly,
        // Fit the validating format.
        //fazer o formater para dinheiro
        CurrencyInputFormatter()
    ],
    keyboardType: TextInputType.number, ...  

TextInputFormatter

class CurrencyInputFormatter extends TextInputFormatter {

    TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {

        if(newValue.selection.baseOffset == 0){
            print(true);
            return newValue;
        }

        double value = double.parse(newValue.text);

        final formatter = NumberFormat.simpleCurrency(locale: "pt_Br");

        String newText = formatter.format(value/100);

        return newValue.copyWith(
            text: newText,
            selection: new TextSelection.collapsed(offset: newText.length));
    }
}

This is the result of the code:

enter image description here

8
  • Hello, where did the class NumberFormat() come from? Oct 12, 2018 at 11:57
  • 4
    Hello, it comes from this library pub.dartlang.org/packages/intl Oct 13, 2018 at 12:07
  • 2
    Hello @JorgeVieira, the code works but with a little problem, the input of zeros don't work. e.g. I can't type the number "500", the last two zeros don't enter. Feb 14, 2019 at 21:19
  • noting TextInputFormatter comes from import 'package:flutter/services.dart';
    – dpjanes
    Feb 28, 2019 at 13:51
  • 1
    It is very useful, you can use in another ways. i am using this for formatting different type of fields. May 8, 2020 at 9:09
38

An easy solution to set a custom money mask, is to use the flutter_masked_text package:

1 - First of all, you need add this packege to your package's pubspec.yaml file:

dependencies:
  flutter_masked_text: ^0.7.0

2 - After that, install the package using the command line (as below), or use a graphic interface for it, if you are using the IntelliJ IDEA just click in the button "Packages get".

flutter packages get

3 - Now in your Dart code, import it...

import 'package:flutter_masked_text/flutter_masked_text.dart';

4 - Lastly, change your TextField controller code from "TextEditingController" to "MoneyMaskedTextController":

  //final lowPrice = TextEditingController(); //before
  final lowPrice = MoneyMaskedTextController(decimalSeparator: '.', thousandSeparator: ','); //after
6
  • 1
    Yes, @Fellipe Sanches, this is better as i told in the top, i will mark you reply, thank you. Mar 1, 2019 at 14:03
  • 12
    Package is buggy and cursor jumps around, and on some devices backspace does not work well
    – lawonga
    Apr 12, 2019 at 18:20
  • 1
    I also have the issue with the MoneyMaskedTextController, that whenever I type the cursor jumps to the beginning of the filed. Any ideas how to resolve this?
    – Petr
    Aug 27, 2019 at 8:21
  • 1
    final rendaMensalController = MoneyMaskedTextController(decimalSeparator: '.', thousandSeparator: ',', leftSymbol: 'R\$'); to display the coin type on the left. Nov 15, 2020 at 13:59
  • 1
    nullsafety version pub.dev/packages/flutter_masked_text2 Oct 27, 2021 at 5:02
33

enter image description here


Use intl package. Full code:

import 'package:intl/intl.dart';

class _HomePageState extends State<HomePage> {
  final _controller = TextEditingController();
  static const _locale = 'en';
  String _formatNumber(String s) => NumberFormat.decimalPattern(_locale).format(int.parse(s));
  String get _currency => NumberFormat.compactSimpleCurrency(locale: _locale).currencySymbol;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: TextField(
        controller: _controller,
        decoration: InputDecoration(prefixText: _currency),
        keyboardType: TextInputType.number,
        onChanged: (string) {
          string = '${_formatNumber(string.replaceAll(',', ''))}';
          _controller.value = TextEditingValue(
            text: string,
            selection: TextSelection.collapsed(offset: string.length),
          );
        },
      ),
    );
  }
}
6
  • 2
    You saved me. I had a problem as I was assigning the String from the onChanged call-back to the control.text directly.. this would freeze the cursor path the beginning of the textfield.. hence writing the imputed text reversed.. I was also using the controller.text.length to offset selection instead that the onChanged String . Thank you very much.
    – Vincenzo
    Feb 4, 2021 at 13:52
  • how to change comma with dot ? Apr 6, 2021 at 9:32
  • @RohmatulLaily The comma is coming from compactSimpleCurrency, if your locale allows dot, it will automatically be added.
    – CopsOnRoad
    Apr 6, 2021 at 9:39
  • 4
    This worked fine on integer but not worked for values with decimal eg: 1,234.90. It caused the TextField to stop at 1,234. Any workaround for this condition?
    – luke77
    May 6, 2021 at 16:31
  • Does not work as needed. It moved the cursor to the end every time 👎
    – jujka
    Dec 6, 2022 at 14:13
9

This library works perfect for me:

https://pub.dev/packages/currency_text_input_formatter

...
inputFormatters: [
  CurrencyTextInputFormatter(
    decimalDigits: 0,
    locale: 'ru',
  )
]
...
1
  • 1
    Using this package, will move your cursor to the end to the text, so if the user needs to change something in the middle of the text the cursor will be set at the end, this behavior is really annoying. There is a open Issue at the repo. Apr 25, 2022 at 15:02
5

Updated the code from @AndréLuis to limit the number of digits (maxDigits), thanks for sharing.

import 'package:flutter/services.dart';
import 'package:intl/intl.dart';

class CurrencyPtBrInputFormatter extends TextInputFormatter {
  CurrencyPtBrInputFormatter({this.maxDigits});
  final int maxDigits;

  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {

    if (newValue.selection.baseOffset == 0) {
      return newValue;
    }

    if (maxDigits != null && newValue.selection.baseOffset > maxDigits) {
      return oldValue;
    }

    double value = double.parse(newValue.text);
    final formatter = new NumberFormat("#,##0.00", "pt_BR");
    String newText = "R\$ " + formatter.format(value / 100);
    return newValue.copyWith(
        text: newText,
        selection: new TextSelection.collapsed(offset: newText.length));
  }
}

Use the code bellow for the TextFormField, I'm also parsing the value to double, removing the non-digit chars using RegExp.

TextFormField(
  maxLines: 1,
  keyboardType: TextInputType.number,
  inputFormatters: [
    WhitelistingTextInputFormatter.digitsOnly,
    CurrencyPtBrInputFormatter(maxDigits: 8),
  ],
  onSaved: (value) {
    String _onlyDigits = value.replaceAll(RegExp('[^0-9]'), "");
    double _doubleValue = double.parse(_onlyDigits) / 100;
    return _valor = _doubleValue;
  },
);
2

To make a cleaner code the umasked value could be included in the Formatter class as a method. So when the value got changed you will be able to call it and simplifying the code.

Widget build(BuildContext context) {
    var maskFormatter = new CurrencyPtBrFormatter(maxDigits: 12);
    return Scaffold(
        body: SingleChildScrollView(
            controller: _scrollController,
            child: Column(
              children: <Widget>[
                TextField(
                  keyboardType: TextInputType.number,
                  inputFormatters: [
                    WhitelistingTextInputFormatter.digitsOnly,
                    maskFormatter,
                  ],
                  controller: _yourController,
                  onChanged: (value) {
                    print(maskFormatter.getUnmaskedDouble()); // here the umasked value
                  },
                  onEditingComplete: () {
                    mudarFocoCampo(context, _estoqueFocus, _codigoFocus);
                  },
                )
              ],
            )));
  }

Here the complete formatter with umasked method.

import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
class CurrencyPtBrFormatter extends TextInputFormatter {
  CurrencyPtBrFormatter({this.maxDigits});
  final int maxDigits;
  double _uMaskValue;
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.selection.baseOffset == 0) {
      return newValue;
    }
    if (maxDigits != null && newValue.selection.baseOffset > maxDigits) {
      return oldValue;
    }
    double value = double.parse(newValue.text);
    final formatter = new NumberFormat("#,##0.00", "pt_BR");
    String newText = "R\$ " + formatter.format(value / 100);
    //setting the umasked value
    _uMaskValue = value / 100;
    return newValue.copyWith(
        text: newText,
        selection: new TextSelection.collapsed(offset: newText.length));
  }
  //here the method
  double getUnmaskedDouble() {
    return _uMaskValue;
  }
}
2

I have a very great solution to this kind of formation of money. You do not need to implement any packages.

In this case, we create the NumericTextFormatter class and write the following code.

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

class NumericTextFormatter 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) {
    final int selectionIndexFromTheRight = newValue.text.length -newValue.selection.end;
  var value = newValue.text;
  if (newValue.text.length > 2) {
    value = value.replaceAll(RegExp(r'\D'), '');
    value = value.replaceAll(RegExp(r'\B(?=(\d{3})+(?!\d))'), ' ');
    print("Value ---- $value");
  }
  return TextEditingValue(
    text: value,
    selection: TextSelection.collapsed(offset: value.length -selectionIndexFromTheRight),);
} else {
  return newValue;
}
}}

And in the TextFormField () widget, we can call the NumericTextFormatter class in the inputFormatters parameter.

           // Example 
                 TextField(
                    controller: productCostController,
                    keyboardType: TextInputType.number,
                    inputFormatters: [
                      NumericTextFormatter(),
                      LengthLimitingTextInputFormatter(20),
                    ],
                    decoration: InputDecoration(
                        border: new OutlineInputBorder(
                          borderRadius: BorderRadius.circular(13),
                          borderSide: new BorderSide(
                            color: Colors.blue,
                          ),
                        ),
                        hintText: "Product price",
                      ),
                  ),
1
  • This certainly works like charm, for those looking for comma instead of space as used in the answer, here you go value = value.replaceAll(RegExp(r'\B(?=(\d{3})+(?!\d))'), ','); Oct 29, 2022 at 0:26
1

Using pattern_formatter package,

TextField(
  keyboardType: TextInputType.number,
  inputFormatters: [
    ThousandsFormatter()
  ],
)
1

Tried all recommended packages, they all have some issues, flutter_multi_formatter is the nearly perfect one.

TextFormField(
    keyboardType: TextInputType.number,
    inputFormatters: [
        MoneyInputFormatter(
            trailingSymbol: MoneySymbols.EURO_SIGN,
            useSymbolPadding: true,
            mantissaLength: 3 // the length of the fractional side
        )
    ],
),
0
0

some of the answers didn't work for me, I had to change and mix some of the solutions, and here is what is working with the right to left input and autoformat.

                    child: TextField(
                  onTap: () {
                    _iquantidade.selection = TextSelection(
                        baseOffset: 0,
                        extentOffset: _iquantidade.text.length);
                  },
                  controller: _iquantidade,
                  keyboardType: const TextInputType.numberWithOptions(),
                  inputFormatters: [
                    formataNumeros,
                    BRNumberInputFormatter()
                  ],

Filtering formater

FilteringTextInputFormatter formataNumeros =
FilteringTextInputFormatter(RegExp(r'[^0-9]'), allow: true);

and the class BRNumberFormater

class BRNumberInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
    TextEditingValue oldValue, TextEditingValue newValue) {
  if (newValue.selection.baseOffset == 0) {
    return newValue;
  }
  double value = double.parse(newValue.text) / 100;
  final formatter = NumberFormat("#,##0.00", "pt_BR");
  String newText = formatter.format(value);
  return newValue.copyWith(
      text: newText,
      selection: TextSelection.collapsed(offset: newText.length));
}

}

0
   final TextEditingController _controller = TextEditingController();
   String _formatNumber(String s) => NumberFormat.decimalPattern('en').format(int.parse(s));
   String get _currency => NumberFormat.compactSimpleCurrency(locale: 'en').currencySymbol;
    
    TextField(
     controller: _controller,
     onChanged: (String string) {
     string = '${_formatNumber(string.replaceAll(',', ''))}';
     _controller.value = TextEditingValue(
        text: string,
        selection: TextSelection.collapsed(offset: string.length),
        );
      },
    )
-1

Here is an improved solution based on the answer of @Cassio Seffrin. The problem with his solution was that it didn't enable deletion if the currency was placed after the amount. In euro we write 42,43€ and not EUR42,43, this means when we press the deletion key, we need to tell to the formatter to go delete the correct digits.

The following code will work perfectly. The advantage of this solution is that you have more freedom to modify things. And unlike the flutter_masked_text package, you can use it with a textEditingController from the Hook package.

import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
TextFormField(
        controller: textEditingController,
        ...,
        inputFormatters: [
             FilteringTextInputFormatter.digitsOnly,
             CurrencyInputFormatter(),
        ],

)
class CurrencyInputFormatter extends TextInputFormatter {
  CurrencyInputFormatter({this.maxDigits = 10});
  final int maxDigits;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.selection.baseOffset == 0) {
      return newValue;
    }
    if (newValue.selection.baseOffset > maxDigits) {
      return oldValue;
    }

    final oldValueText = oldValue.text.replaceAll(RegExp(r'[^0-9]'), '');
    String newValueText = newValue.text;

    // We manually remove the value we want to remove
    // If oldValueText == newValue.text it means we deleted a non digit number.
    if (oldValueText == newValue.text) {
      newValueText = newValueText.substring(0, newValue.selection.end - 1) +
          newValueText.substring(newValue.selection.end, newValueText.length);
    }

    double value = double.parse(newValueText);
    final formatter = NumberFormat.currency(locale: 'eu', symbol: '€');
    String newText = formatter.format(value / 100);

    return newValue.copyWith(
        text: newText,
        selection: TextSelection.collapsed(offset: newText.length));
  }
}
2
  • Have you even tried running it before posting this answer? It does not work AT ALL 😂
    – jujka
    Dec 6, 2022 at 14:10
  • I use it regularly in my code and it works.
    – RominHood
    Dec 6, 2022 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.