Orientação gerada a partir de informações públicas. Apenas para referência.
flutter_multi_formatter é um pacote Flutter que fornece formatação de números de telefone internacionais, formatação de cartões de crédito/débito e formatação de entrada com máscara personalizável. Ele simplifica a entrada do usuário aplicando automaticamente regras de formatação enquanto o usuário digita, melhorando a usabilidade e reduzindo erros. O pacote suporta múltiplas plataformas, incluindo Android, iOS, Web, macOS, Windows e Linux, tornando-o ideal para aplicações multiplataforma que exigem um tratamento robusto de entrada. Integra-se perfeitamente aos campos de texto do Flutter e fluxos de validação.
Casos de uso
Entrada de número de telefone internacional
Formatação de número de cartão de crédito/débito
Entrada mascarada para IDs ou códigos
Validação de dados do formulário
Experiências de entrada amigáveis ao usuário
Manipulação de formulários multiplataforma
Principais recursos
Suporta formatação de número de telefone internacional
Formatadores de cartão de crédito/débito embutidos
Padrões de máscara personalizáveis
Formatação de entrada em tempo real
Implementação independente de plataforma
Integração fácil com TextFormField
Indicado para
Desenvolvedores criando formulários com validação de entrada
Aplicativos voltados para públicos globais
Funcionalidades de verificação de pagamento ou identidade
Aplicativos móveis e web multiplataforma
design de entrada focado em UX
Aplicações que exigem formatação em tempo real
Considerações
Pode ser necessário lógica de validação adicional para casos extremos
Máscaras personalizadas precisam de testes cuidadosos
Impacto no desempenho em cenários de entrada de alta frequência
Limitado a tipos específicos de formatador
Não adequado para mascaramento dinâmico complexo
Depende da configuração correta para o comportamento desejado
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
flutter_multi_formatter
If you want to support my development you can donate some ETH / USDT0xaDed99fda2AA53B3aFC8bB2d27b14910dB9CEdA1
Digit extractor (allows to extract all digits out of a string)
Phone number validator (the check is based on country phone codes and masks so it's a more serious and reliable validation than a simple regular expression)
"Is digit" checker (Simply checks if an input string value a digit or not)
Currency string formatter (allows to convert a number to a currency string representation e.g. this 10000 to this 10,000.00$)
Unfocuser (a widget that is used to unfocus any text fields without any boilerplate code. Extremely simple to use)
PinyinUtils class that contains a few useful methods to work with chinese
pinyin
PinyinUtils.clearPunctuation : removes all punctuations from a string, including special chinese punctuation
PinyinUtils.containsTone: returns true if a string contains some tone. False otherwise
PinyinUtils.getPinyinTones returns a list of int's with all syllable tones in a sentence
PinyinUtils.getPinyinTone the same as PinyinUtils.getPinyinTones but for a single syllable. Returns its tone. 5 means neutral tone
PinyinUtils.splitToSyllables: a generic function that can accept String or SyllableData as a generic constraint and return a list of objects of this type. SyllableData is more advanced then just a string. Use it if you need to know if a string is a valid pinyin as well as its tone
Formatting a phone
PhoneInputFormatter.replacePhoneMask(
countryCode: 'RU',
newMask: '+0 (000) 000 00 00',
);
PhoneInputFormatter.addAlternativePhoneMasks(
countryCode: 'BR',
alternativeMasks: [
'+00 (00) 0000-0000',
'+(00) 00000',
'+00 (00) 00-0000',
],
);
/// There is also a possibility to enter endless phones /// by setting allowEndlessPhone to true /// this means that you can enter a phone number of any length/// its part that matches a mask will be formatted /// and the rest will be entered unformatted/// is will allow you to support any phones (even those that are not supported by the formatter yet)PhoneInputFormatter(
onCountrySelected: _onCountrySelected,
allowEndlessPhone: true,
)
/// for phone numbers with a fully automated detectionPhoneInputFormatterPinyinFormatter/// for anything that can be maskedMaskedInputFormatter/// for credit / debit cardsCreditCardNumberInputFormatterCreditCardCvcInputFormatterCreditCardExpirationDateFormatter/// for currenciesCurrencyInputFormatterPosInputFormatter
Utility methods and widgets
Validates Bitcoin wallets (also supports bech32)
You can use these example wallets to test the validator
P2PKH addresses start with the number 1Example: 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2
P2SH addresses start with the number 3Example: 3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy
Bech32 addresses also known as "bc1 addresses" start with bc1Example: bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq
/// a simple check if its a BTC wallet or not, regardless of its typeboolisBitcoinWalletValid(String value);
/// a bit more complicated check which can return the type of /// BTC wallet and return SegWit (Bech32), Regular, or None if /// the string is not a BTC addressBitcoinWalletTypegetBitcoinWalletType(String value);
/// Detailed check, for those who need to get more details /// of the wallet. Returns the address type, the network, and /// the wallet type along with its address. /// It always returns BitcoinWalletDetails object. To check if it's/// valid or not use bitcoinWalletDetails.isValid getter/// IMPORTANT The BitcoinWalletDetails class overrides an /// equality operators so two BitcoinWalletDetails objects can be /// compared simply like this bwd1 == bwd2BitcoinWalletDetailsgetBitcoinWalletDetails(String? value);
Gets all numbers out of a string and joins them into a new string
e.g. a string like fGgfjh456bb78 will be converted into this: 45678
toCurrencyString() is used by the CurrencyInputFormatter internally
but you can also use it directly
import'package:flutter_multi_formatter/flutter_multi_formatter.dart';
StringtoCurrencyString(String value, {
int mantissaLength = 2,
/// in case you need a period as a thousand separator/// simply change ThousandSeparator.Comma to ThousandSeparator.Period/// and you will get 1.000.000,00 instead of 1,000,000.00ThousandSeparator thousandSeparator = ThousandSeparator.Comma,
ShorteningPolicy shorteningPolicy = ShorteningPolicy.NoShortening,
String leadingSymbol = '',
String trailingSymbol = '',
bool useSymbolPadding = false
});
print(toCurrencyString('123456', leadingSymbol: CurrencySymbols.DOLLAR_SIGN)); // $123,456.00/// the values can also be shortened to thousands, millions, billions... /// in this case a 1000 will be displayed as 1K, and 1250000 will turn to this 1.25Mvar result = toCurrencyString(
'125000',
leadingSymbol: CurrencySymbols.DOLLAR_SIGN,
shorteningPolicy: ShorteningPolicy.RoundToThousands
); // $125K
result = toCurrencyString(
'1250000',
leadingSymbol: CurrencySymbols.DOLLAR_SIGN,
shorteningPolicy: ShorteningPolicy.RoundToMillions
); // 1.25M
There's also an "extension" version of this function which can be used on
double, int and String.
Automatically detects the country the phone number belongs to and formats the number according
to its mask.
You don't have to care about keeping track of the list of countries or anything else.
The whole process is completely automated.
You simply add this formatter to the list of formatters like this:
CreditCardNumberInputFormatter automatically detects a type of a card based on a predefined
list of card system and formats the number accordingly.
This detection is pretty rough and may not work with many card system.
All supported systems are available as string constants in
Anyway, if the number is not supported it will just be returned as it is and your input will not
break because of that
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
CreditCardNumberInputFormatter(onCardSystemSelected: (CardSystemData cardSystemData) {
print(cardSystemData.system);
});
],
),
/// there's also a method to format a number as a card number/// the method is located in a credit_card_number_input_formatter.dart fileStringformatAsCardNumber(
String cardNumber, {
bool useSeparators = true,
});
/// and a method to check is a card is validboolisCardNumberValid(requiredString cardNumber,
bool checkLength = false,
bool useLuhnAlgo = true,
});
/// but it will return true only if the card system is supported, /// so you should not really rely on that
Masked formatter
MaskedInputFormatter()
This formatter allows you to easily format a text by a mask
This formatter processes current text selection very carefully so that input does not
feel unnatural
Use it like any other formatters
/// # matches any character and 0 matches digits/// so, in order to format a string like this GHJ45GHJHN to GHJ-45-GHJHN/// use a mask like thisTextFormField(
keyboardType: TextInputType.phone,
inputFormatters: [
MaskedInputFormatter('###-00-#####')
],
),
But in case you want # (hash symbol) to match only some particular values, you can pass
a regular expression to [anyCharMatcher] parameter
/// in this scenario, the # symbol will only match uppercase latin lettersTextFormField(
keyboardType: TextInputType.phone,
inputFormatters: [
MaskedInputFormatter('###-00-#####', anyCharMatcher: RegExp(r'[A-Z]'))
],
),
Money Input formatter
CurrencyInputFormatter()
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
CurrencyInputFormatter(
leadingSymbol: CurrencySymbols.DOLLAR_SIGN
)
],
),
...
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
CurrencyInputFormatter
trailingSymbol: CurrencySymbols.EURO_SIGN,
useSymbolPadding: true,
mantissaLength: 3// the length of the fractional side
)
],
),
Point of Sale input formatter
PosInputFormatter
Allows you to enter numbers like you would normally do
on a sales terminal
Allows to split a phrase into pinyin syllables
e.g. wohenhaonine?
will turn into
wo'hen'hao'ni'ne?
It works irregarding tones, so you can enter text with plain english
characters and it will still work