flutter_multi_formatter 1.1.6

  • Readme
  • Changelog
  • Example
  • Installing
  • 92

flutter_multi_formatter #

This package contains formatters for international phone numbers, credit / debit cards, currencies and a masked formatter

Formatting a phone

Formatting a credit / debit card

Formatting currencies

Using: #

import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

A list of formatters included #

/// for phone numbers with a fully automated detection
PhoneInputFormatter
/// for anything that can be masked
MaskedInputFormater
/// for credit / debit cards
CreditCardNumberInputFormatter
CreditCardCvcInputFormatter
CreditCardExpirationDateFormatter
/// for currencies
MoneyInputFormatter

Utility methods and widgets #

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

import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

String toNumericString(String text);

returns 'true' if the checked characted is digit

import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

bool isDigit(String character);

toCurrencyString() is used by the MoneyInputFormatter internally but you can also use it directly

import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

String toCurrencyString(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.00
    ThousandSeparator thousandSeparator = ThousandSeparator.Comma,
    ShorteningPolicy shorteningPolicy = ShorteningPolicy.NoShortening,
    String leadingSymbol = '',
    String trailingSymbol = '',
    bool useSymbolPadding = false
});

print(toCurrencyString('123456', leadingSymbol: MoneyInputFormatter.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.25M
var result = toCurrencyString(
    '125000', 
    leadingSymbol: MoneyInputFormatter.DOLLAR_SIGN,
    shorteningPolicy: ShorteningPolicy.RoundToThousands
); // $125K

result = toCurrencyString(
    '1250000', 
    leadingSymbol: MoneyInputFormatter.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 but before using it, make sure you use dart sdk version 2.6+ open pubspec.yaml and check this section:

environment:
  sdk: ">=2.6.0 <3.0.0"
import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

var someNumericValue = 123456;
print(someNumericValue.toCurrencyString(leadingSymbol: MoneyInputFormatter.DOLLAR_SIGN)); // $123,456.00

var someNumericStringValue = '123456';
print(someNumericStringValue.toCurrencyString(trailingSymbol: MoneyInputFormatter.EURO_SIGN)); // 123,456.00€

/// it's a widget
Unfocuser

Unfocuser allows you to unfocus any text input and hide the onscreen keyboard when you tap outside of a text input. Use it like this:

@override
Widget build(BuildContext context) {
return Unfocuser(
    child: Scaffold(
    body: SingleChildScrollView(
        child: Padding(
        padding: const EdgeInsets.all(30.0),
        child: Form(
            key: _formKey,
            child: Column(
            children: <Widget>[
                TextFormField(
                keyboardType: TextInputType.phone,
                inputFormatters: [
                    PhoneInputFormatter()
                ],
                ),
            ],
            ),
        ),
        ),
    ),
    ),
);
}

More detailed description #

PhoneInputFormatter

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:

TextFormField(
    keyboardType: TextInputType.phone,
    inputFormatters: [
        PhoneInputFormatter()
    ],
),

You can also get a country data for the selected phone number by simply passing a calback function to your formatter

TextFormField(
    keyboardType: TextInputType.phone,
    inputFormatters: [
        PhoneInputFormatter(onCountrySelected:  (PhoneCountryData countryData) {
            print(countryData.country);
        });
    ],
),
CreditCardNumberInputFormatter

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

class CardSystem {
  static const String VISA = 'Visa';
  static const String MASTERCARD = 'Mastercard';
  static const String JCB = 'JCB';
  static const String DISCOVER = 'Discover';
  static const String MAESTRO = 'Maestro';
  static const String AMERICAN_EXPRESS= 'Amex';
}

Anyway, if the number is not supported it will just be returned as 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 file
String formatAsCardNumber(
String cardNumber, {
    bool useSeparators = true,
});

/// and a method to check is a card is valid
bool isCardValidNumber(String cardNumber);
/// but it will return true only if the card system is supported, 
/// so you should not really rely on that

Masked formatter #

MaskedInputFormater

This formatter allows you to easily format a text by a mask This formatter processes current text selection very carefully so that itput 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 this
TextFormField(
    keyboardType: TextInputType.phone,
    inputFormatters: [
        MaskedInputFormater('###-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 letters
TextFormField(
    keyboardType: TextInputType.phone,
    inputFormatters: [
        MaskedInputFormater('###-00-#####', anyCharMatcher: RegExp(r'[A-Z]'))
    ],
),

Money Input formatter #

MoneyInputFormatter
TextFormField(
    keyboardType: TextInputType.number,
    inputFormatters: [
        MoneyInputFormatter(
            leadingSymbol: MoneyInputFormatter.DOLLAR_SIGN
        )
    ],
),
...

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

For more details see example project. And feel free to open an issue if you find any bugs of errors

[1.1.6] #

  • Added a possibility to use a period as a thousand separator

[1.1.5] #

  • Added support for 6 card systems for now. If the card number is detected as one of the supported systems, e.g. Mastercard, it will be formatted automatically and the callback with CardSystemData argument will be called
  • CreditCardHolderNameFormatter was completely removed. There's no need for this formatter
  • CreditCardNumberFormatter was replaced with CreditCardNumberInputFormatter which is more flexible
  • CvvCodeFormatter was renamed to CreditCardCvcInputFormatter
  • CreditCardExpirationDateFormatter was renamed to CreditCardExpirationDateFormatter

[1.1.1] #

  • Fixed a bug in masked input formatter which allowed to enter an odd symbol in some circumstances

[1.1.0] #

  • Added MoneyInputFormatter

[1.0.3] #

  • Initial pub release. Includes a list of formatters:

PhoneInputFormatter MaskedInputFormater CreditCardNumberFormatter CvvCodeFormatter CreditCardExpirationDateFormatter CreditCardHolderNameFormatter

example/lib/main.dart

import 'package:example/pages/credit_card_format_page.dart';
import 'package:example/pages/money_format_page.dart';
import 'package:example/pages/phone_format_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Multi formatter demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

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

class _MyHomePageState extends State<MyHomePage> {

  void openPage(Widget page) {
    Navigator.of(context).push(CupertinoPageRoute(
      builder: (BuildContext context) {
        return page;
      }
    ));
  }


  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(
        title: Text('Formatters Demo App'),
        centerTitle: true,
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(30.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.lightGreen,
                  onPressed: () {
                    openPage(PhoneFormatPage());
                  },
                  child: Row(
                    children: <Widget>[
                      Icon(Icons.phone),
                      Expanded(child: Center(child: Text('Phone Formatter Demo'))),
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 50.0,
              ),
              Container(
                height: 50,
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.lightBlue,
                  onPressed: () {
                    openPage(CreditCardFormatPage());
                  },
                  child: Row(
                    children: <Widget>[
                      Icon(Icons.credit_card),
                      Expanded(child: Center(child: Text('Credit Card Formatter Demo'))),
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 50.0,
              ),
              Container(
                height: 50,
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.orange,
                  onPressed: () {
                    openPage(MoneyFormatPage());
                  },
                  child: Row(
                    children: <Widget>[
                      Icon(Icons.attach_money),
                      Expanded(child: Center(child: Text('Money formatter'))),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_multi_formatter: ^1.1.6

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
84
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
92
Learn more about scoring.

We analyzed this package on May 24, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0

Health suggestions

Format lib/flutter_multi_formatter.dart.

Run flutter format to format lib/flutter_multi_formatter.dart.

Format lib/formatters/credit_card_cvc_input_formatter.dart.

Run flutter format to format lib/formatters/credit_card_cvc_input_formatter.dart.

Format lib/formatters/credit_card_expiration_input_formatter.dart.

Run flutter format to format lib/formatters/credit_card_expiration_input_formatter.dart.

Fix additional 9 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/formatters/credit_card_number_input_formatter.dart (Run flutter format to format lib/formatters/credit_card_number_input_formatter.dart.)
  • lib/formatters/formatter_extension_methods.dart (Run flutter format to format lib/formatters/formatter_extension_methods.dart.)
  • lib/formatters/formatter_utils.dart (Run flutter format to format lib/formatters/formatter_utils.dart.)
  • lib/formatters/masked_input_formatter.dart (Run flutter format to format lib/formatters/masked_input_formatter.dart.)
  • lib/formatters/money_input_enums.dart (Run flutter format to format lib/formatters/money_input_enums.dart.)
  • lib/formatters/money_input_formatter.dart (Run flutter format to format lib/formatters/money_input_formatter.dart.)
  • lib/formatters/phone_input_enums.dart (Run flutter format to format lib/formatters/phone_input_enums.dart.)
  • lib/formatters/phone_input_formatter.dart (Run flutter format to format lib/formatters/phone_input_formatter.dart.)
  • lib/utils/unfocuser.dart (Run flutter format to format lib/utils/unfocuser.dart.)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test