Skip to content

Instantly share code, notes, and snippets.

@andre-bahia
Last active April 29, 2024 15:06
Show Gist options
  • Save andre-bahia/14fdb0c751822f848a364b3129df1fed to your computer and use it in GitHub Desktop.
Save andre-bahia/14fdb0c751822f848a364b3129df1fed to your computer and use it in GitHub Desktop.
Flutter TextInputFormatter Currency pt_BR
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
class CurrencyPtBrInputFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if(newValue.selection.baseOffset == 0){
return newValue;
}
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));
}
}
// how to use
Widget _fieldValues() {
return Padding(
padding: EdgeInsets.only(top: 10, bottom: 60),
child: TextFormField(
decoration: InputDecoration(
icon: Icon(Icons.monetization_on),
labelText: 'Valor *',
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
CurrencyPtBrInputFormatter()
]
);
}
@ffranzim
Copy link

Poderia me informar de onde vem o WhitelistingTextInputFormatter?

@andre-bahia
Copy link
Author

Fala @ffranzim, é do proprio core do flutter.

Dei uma pesquisada aqui e essa classe foi depreciada.
https://docs.flutter.dev/release/breaking-changes/2-5-deprecations#blacklistingtextinputformatter--whitelistingtextinputformatter

E foi alterada para FilteringTextInputFormatter.digitsOnly , teria que alterar e testar.

Como tem um tempo que fiz esse formatter pode ter algum efeito colateral.

@andre-bahia
Copy link
Author

Isso mesmo @ffranzim, fiz o teste aqui e funcionou.
Alterei o código acima.
Só não esquecer de importar o import 'package:flutter/services.dart';

@ffranzim
Copy link

Valeu!
Eu tinha achado, vacilo meu não postar!
Obrigado

@andre-bahia
Copy link
Author

🚀

@rubgithub
Copy link

rubgithub commented Oct 5, 2022

Olá, como ficaria para aceitar digitação da esquerda pra direita?
exemplo, se digitar
2 = 2,00
201 = 2,01
210 = 2,10

@matheusess
Copy link

Código mágico, salvo minha pele rsrs

@lpcastelo
Copy link

Código muito bom, mandou bem de mais!!

@KleJr
Copy link

KleJr commented Oct 17, 2023

Código muito bom. top

@h0landa
Copy link

h0landa commented Oct 31, 2023

Top de vdd

@MarioHBS
Copy link

MarioHBS commented Nov 1, 2023

Até que enfim, depois de ter deixado um código de lado um tempo ele parou de funcionar essa funcionalidade.
O seu resolveu meu problema, valeu !

@johannfurtado
Copy link

obrigado lenda

@EdsonVanderlei
Copy link

EdsonVanderlei commented Dec 5, 2023

Jesus, Maria e José tu fez amor com o código <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment