A masked text for Flutter.

Overview

flutter_masked_text

Masked text input for flutter.

travis-ci

logo

Alert

Hi guys!

Unfortunately, I'm not developing mobile anymore. This repo will not receive updates.

Install

Follow this GUIDE

Usage

Import the library

import 'package:flutter_masked_text/flutter_masked_text.dart';

MaskedText

Create your mask controller:

var controller = new MaskedTextController(mask: '000.000.000-00');

Set controller to your text field:

return new MaterialApp(
    title: 'Flutter Demo',
    theme: new ThemeData(
        primarySwatch: Colors.blue,
    ),
    home: new SafeArea(
        child: new Scaffold(
            body: new Column(
                children: <Widget>[
                    new TextField(controller: controller,) // <--- here
                ],
            ),
        ),
    ),
);

This is the result:

sample

Mask Options

In mask, you can use the following characters:

  • 0: accept numbers
  • A: accept letters
  • @: accept numbers and letters
  • *: accept any character

Initial Value

To start a mask with initial value, just use text property on constructor:

var controller = new MaskedTextController(mask: '000-000', text: '123456');

Update text programaticaly

If you want to set new text after controller initiatialization, use the updateText method:

var controller = new MaskedTextController(text: '', mask: '000-000');
controller.updateText('123456');

print(controller.text); //123-456

Using custom translators

If you want to use your custom regex to allow values, you can pass a custom translation dictionary:

const translator = {
    '#': new RegExp(r'my regex here')
};

var controller = new MaskedTextController(mask: '####', translator: translator);

If you want to use default translator but override some of then, just get base from getDefaultTranslator and override what you want (here is a sample for obfuscated credit card):

var translator = MaskedTextController.getDefaultTranslator(); // get new instance of default translator.
translator.remove('*'); // removing wildcard translator.

var controller = new MaskedTextController(mask: '0000 **** **** 0000', translator: translator);
controller.updateText('12345678');

print(controller.text); //1234 **** **** 5678

Change the mask in runtime

You can use the updateMask method to change the mask after the controller was created.

var cpfController = new MaskedTextController(text: '12345678901', mask: '000.000.000-00');

print(cpfController.text); //'123.456.789-01'

cpfController.updateMask('000.000.0000-0');

print(cpfController.text); //'123.456.7890-1'

Hook: beforeChange [v0.7.0+]

In some cases, you will want to validate the mask value to decide if it's allowed to input or not.

It's simple: you just need to set the beforeChange and return true or false. If you return true, it will accept the new value and will try to apply the mask. Otherwhise, it will reject the new value.

The function receives two parameters:

  • previous: the previous text of the controller.
  • next: the next text that will be masked.
var controller = new MaskedTextController(mask: '(00) 0000-0000');
controller.beforeChange = (String previous, String next) {
    // my logic here

    return true;
};

Hook: afterChange [v0.7.0+]

This function will be called after setted in the controller.

The function receives two parameters:

  • previous: the previous text of the controller.
  • next: the next text that will be masked.
var controller = new MaskedTextController(mask: '(00) 0000-0000');
controller.afterChange = (String previous, String next) {
    print("$previous | $next");
};

Money Mask

To use money mask, create a MoneyMaskedTextController:

var controller = new MoneyMaskedTextController();

//....
new TextField(controller: controller, keyboardType: TextInputType.number)

Decimal and Thousand separator

It's possible to customize decimal and thousand separators:

var controller = new MoneyMaskedTextController(decimalSeparator: '.', thousandSeparator: ',');

Set value programaticaly

To set value programaticaly, use updateValue:

controller.updateValue(1234.0);

Get double value

To get the number value from masked text, use the numberValue property:

double val = controller.numberValue;

Using decoration symbols

You can use currency symbols if you want:

// left symbol
var controller = new MoneyMaskedTextController(leftSymbol: 'R\$ ');
controller.updateValue(123.45);

print(controller.text); //<-- R$ 123,45


// right symbol
var controller = new MoneyMaskedTextController(rightSymbol: ' US\$');
controller.updateValue(99.99);

print(controller.text); //<-- 99,99 US$


// both
var controller = new MoneyMaskedTextController(leftSymbol: 'to pay:', rightSymbol: ' US\$');
controller.updateValue(123.45);

print(controller.text); //<-- to pay: 123,45 US$

hook: afterChange [v0.7.0+]

You can watch for mask and value changes. To do this, just set the afterChange hook.

This function receives two parameters:

  • masked: the masked text of the controller.
  • raw: the double value of the text.
var controller = new MoneyMaskedTextController();

controller.afterChange = (String masked, double raw) {
    print("$masked | $raw");
};

Defining decimal places [v0.8.0+]

You can define the number of decimal places using the precision prop:

var controller = new MoneyMaskedTextController(precision: 3);
controller.updateValue(123.45);

print(controller.text); //<-- 123,450

Using default TextEditingController

The MaskedTextController and MoneyMaskedTextController extends TextEditingController. You can use all default native methods from this class.

Samples

You can check some code samples in this repo: flutter-masked-text-samples

TODO

  • Custom translations
  • Money Mask
  • Raw Text Widget
Comments
  • Is possible to use 2 masks?

    Is possible to use 2 masks?

    I want to use CPF/CNPJ mask.

    So if user input 123.456.789-10 will mask as CPF and if it continues to input, will change to CNPJ mask... there is a way?

    opened by rfschubert 10
  • Pressing checkmark on keyboard clears the value of the field

    Pressing checkmark on keyboard clears the value of the field

      TextFormField _phoneField() {
        MaskedTextController maskedTextController =
            new MaskedTextController(mask: '000-000-0000');
    
        return TextFormField(
          controller: maskedTextController,
          decoration: InputDecoration(
              labelText: 'Phone',
              helperText: 'Please use the format XXX-XXX-XXXX.'
          ),
          keyboardType: TextInputType.phone,
        );
    

    The checkmark button on the keyboard should just remove the cursor from the field and hide the keyboard. Not sure why it's clearing the value from the input. Note: happens with other keyboardTypes as well.

    On flutter beta channel, flutter_masked_text 0.6.0

    question investigating 
    opened by dwolfhub 7
  • Invalid double in numberValue when delete value in TextFormField

    Invalid double in numberValue when delete value in TextFormField

    Hello, I'm getting this error in my MoneyMaskedTextController when clear TextFormField error : Type (FormatException) "Invalid double"

    double get numberValue { List parts = _getOnlyNumbers(this.text).split('').toList(growable: true); parts.insert(parts.length - precision, '.'); // value : "." return double.parse(parts.join()); }

    opened by hassanbht 4
  • Change decimal length

    Change decimal length

    Hi,

    First, I want to say thanks for making this extension.

    AFAIK, your MoneyMaskedTextController only supports 2 digits decimal length. Is there any way to change the fraction digits length?

    for example: 1,234,567.789 or 1,234,567.7890 or 1,234,567.78901 or even without decimals like 1,234,567

    Thank you,


    P.S: Sorry for my bad English

    opened by fadhly-permata 4
  • This does not work with TextFormField

    This does not work with TextFormField

    text_form_field.dart': Failed assertion: line 123 pos 15: 'initialValue == null || controller == null': is not true.

    final MoneyMaskedTextController moneyMask = MoneyMaskedTextController();
    TextFormField(
                            controller: moneyMask,
                            decoration: InputDecoration(labelText: 'Currency'),
                            initialValue: 0,
                            keyboardType: TextInputType.numberWithOptions(decimal: true),
                            onChanged: (value) {
                              value = moneyMask.text;
                              print(value);
                            },
                            onSaved: (value) {
                              moneyMask.updateValue(double.parse(value));
                            },
                          ),
    
    opened by chitgoks 3
  • RangeError

    RangeError

    flutter_masked_text: ^0.8.0 If you long press to select a number masked input and then try to key got this error

    RangeError: Invalid value: Not in range 0..1, inclusive: -1

    Screenshot_20190514-115440

    screen-11 58 03 14 05 2019

    question 
    opened by andredealmei 3
  • Disable minus symbol on MoneyMaskedTextController

    Disable minus symbol on MoneyMaskedTextController

    When using the MoneyMaskedTextController with the number keyboard (keyboardType: TextInputType.number) it is possible to enter minus symbols which get appended to the number.

    From my point of view, that should not be the case for a money input.

    opened by tobire 2
  • Add currency symbol to MoneyMaskedTextController

    Add currency symbol to MoneyMaskedTextController

    It would be awesome to have a currency symbol (like € or $) automatically inserted after a money input using the MoneyMaskedTextController.

    Hope you can implement this, thanks for the great plugin!

    enhancement working 
    opened by tobire 2
  • onChanged wrong value

    onChanged wrong value

    onChanged wrong value

    input: 0 input: 1

    TextField(
    	onChanged: (value) {
    	  print('value: $value');
    	},
    	controller: MoneyMaskedTextController(
    		initialValue: 0.00,
            precision: 2,
    	),
    ....
    

    image

    opened by rubgithub 1
  • Add support for Dart greater than 2.0.0

    Add support for Dart greater than 2.0.0

    You restrict it currently to only <=2.0.0. Dart 2.1.0 was released today on the master branch.

    Suggestion:

    environment: sdk: ">=1.23.0 <3.0.0"

    opened by codegrue 1
  • onChanged wrong value

    onChanged wrong value

    onChanged wrong value

    typed: 0 typed: 1

    TextField(
    	onChanged: (value) {
    	  print('value: $value');
    	},
    	controller: MoneyMaskedTextController(
    		initialValue: 0.00,
            precision: 2,
    	),
    ....
    

    image

    opened by rubgithub 0
  • UNFORTUNATELY THIS LIB HAS BEEN ABANDONED BY THE AUTHOR.

    UNFORTUNATELY THIS LIB HAS BEEN ABANDONED BY THE AUTHOR.

    UNFORTUNATELY THIS LIB HAS BEEN ABANDONED BY THE AUTHOR.

    IT'S ONE MORE PEOPLE WHO DOES THINGS WITH THE OBJECTIVE OF BECOMING POPULAR AND WITH THIS RIDICULOUS ATTITUDE HARMFUL TO MANY PROFESSIONALS.

    opened by paulobreim 0
  • Added null safety support

    Added null safety support

    Summary

    • Updated flutter_masked_text.dart
    • Several fixes related to null safety;
    • Updated deprecated code;

    Tested on

    Flutter 3.0.4 • channel stable • https://github.com/flutter/flutter.git Framework • revision 85684f9300 (6 weeks ago) • 2022-06-30 13:22:47 -0700 Engine • revision 6ba2af10bb Tools • Dart 2.17.5 • DevTools 2.12.2

    opened by alishantesch 0
  • moveCursorToEnd doesn't work anymore

    moveCursorToEnd doesn't work anymore

    Hi,

    I'm update android version from my project, to minSdk 20 and targetSdk 30. Apparently after this change the cursor no longer stops at the end of the text, but at the position of the mask. To fix it, I added the following code (Future.delayed) to the plugin. It worked, but I don't know if it's the best thing to do:

      @override
      void set text(String newText) {
        if (super.text != newText) {
          super.text = newText;
          Future.delayed(Duration(milliseconds: 50), this.moveCursorToEnd);
        }
      }
    

    Thanks!

    opened by mobilemindtec 0
Releases(0.8.0)
Owner
Ben-hur Santos Ott
Software engineer, musician, workaholic and power metal lover.
Ben-hur Santos Ott
A Flutter package to parse text and make them into linkified text widget

?? Flutter Parsed text A Flutter package to parse text and extract parts using predefined types like url, phone and email and also supports Regex. Usa

Fayeed Pawaskar 213 Dec 27, 2022
Rich Text renderer that parses Contentful Rich Text JSON object and returns a renderable Flutter widget

Contentful Rich Text Renderer for Flutter Rich Text renderer that parses Contentful Rich Text field JSON output and produces a Flutter Widget tree tha

Kumanu 45 Nov 10, 2022
Soft and gentle rich text editing for Flutter applications.

About Zefyr Soft and gentle rich text editing for Flutter applications. You are viewing early dev preview version of this package which is no longer a

Memspace 2.2k Jan 8, 2023
Flutter widget that automatically resizes text to fit perfectly within its bounds.

Flutter widget that automatically resizes text to fit perfectly within its bounds. Show some ❤️ and star the repo to support the project Resources: Do

Simon Leier 1.8k Jan 3, 2023
A simple Flutter package that makes turning a FAB into a text field easy.

flutter_text_field_fab A simple Flutter widget that makes turning a FAB into a text field easy.

Haefele Software 4 Jan 18, 2022
Soft and gentle rich text editing for Flutter applications

Soft and gentle rich text editing for Flutter applications. Zefyrka is a fork of Zefyr package with the following improvements: support Flutter 2.0 op

null 85 Dec 21, 2022
Arc Text Widget for Flutter

Flutter Arc Text Renders text along the arc. See demo. The story behind the plugin is here. Basic usage class MyApp extends StatelessWidget

Kirill Bubochkin 15 Oct 18, 2021
Text Editor in Flutter for Android and iOS to help free write WYSIWYG HTML code

Flutter Summernote Text Editor in Flutter for Android and iOS to help free write WYSIWYG HTML code based on Summernote 0.8.18 javascript wrapper. NOTI

Chandra Abdul Fattah 41 Sep 12, 2022
A Tricky Solution for Implementing Inline-Image-In-Text Feature in Flutter.

A Tricky Solution for Implementing Inline-Image-In-Text Feature in Flutter.

Bytedance Inc. 646 Dec 29, 2022
A customizable code text field supporting syntax highlighting

CodeField A customizable code text field supporting syntax highlighting Live demo A live demo showcasing a few language / themes combinaisons Showcase

Bertrand 162 Dec 23, 2022
Flutter textfield validation lets you validate different textform fields in your Flutter app

Flutter textfield validation lets you validate different textform fields in your Flutter app

World-Package 2 Sep 15, 2022
A markdown renderer for Flutter.

Flutter Markdown A markdown renderer for Flutter. It supports the original format, but no inline HTML. Overview The flutter_markdown package renders M

Flutter 828 Aug 12, 2021
A Flutter Package to render Mathematics, Physics and Chemistry Equations based on LaTeX

flutter_tex Contents About Demo Video Screenshots How to use? Android iOS Web Examples Quick Example TeXView Document TeXView Markdown TeXView Quiz Te

Shahzad Akram 219 Jan 5, 2023
flutter 中文排版,支持分页上下对齐 两端对齐 翻页动画

text_composition flutter 中文排版 分页 上下对齐 两端对齐 多栏布局 弃用richText,使用Canvas,精确定位绘图位置,消除字体对排版影响 视频与截图 demo https://github.com/mabDc/text_composition/releases/t

西红柿大芝麻 50 Nov 3, 2022
Flutter Tutorial - PDF Viewer - Asset, File, Network & Firebase

Flutter Tutorial - PDF Viewer - Asset, File, Network & Firebase Use the Flutter PDF Viewer to download PDF documents and display them within your Flut

Johannes Milke 36 Dec 9, 2022
Create an AutoComplete TextField to search JSON data based on suggestions in Flutter.

Flutter Tutorial - AutoComplete TextField & AutoComplete Search Create an AutoComplete TextField to search JSON data based on suggestions in Flutter.

Johannes Milke 32 Oct 23, 2022
Flutter phone number input

phone_form_field Flutter phone input integrated with flutter internationalization Features Totally cross platform, this is a dart only package / depen

cedvdb 38 Dec 31, 2022
A low code editor with the full power of flutter.

flutter_blossom ?? Low code editor with the full power of flutter. Think in flutter, watch your ideas come to life, plan ahead and let your creativity

Flutter Blossom 0 Dec 2, 2021
A Flutter package provides some implementations of TextInputFormatter that format input with pre-defined patterns

A Flutter package provides some implementations of TextInputFormatter that format input with pre-defined patterns

HungHD 192 Dec 31, 2022