Git Product home page Git Product logo

flutter-masked-text's People

Contributors

calebeoliveira avatar elzombieisra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter-masked-text's Issues

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());
}

Blocked input on Samsung devices

The code below blocks input on Samsung phones:

final mmTextController = MoneyMaskedTextController(
decimalSeparator: DecimalSeparator,
thousandSeparator: ThousandSeparator,
precision: precision,
);
mmTextController.afterChange = (String maskedValue, double rawValue) {
// the line below blocks any further input on Samsung phones
mmTextController.selection = TextSelection.collapsed(offset: mmTextController.text.length);
};

Email formatter

Great job on this library!

Would love to see e-mail formatter as well.

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.

O cursor vai pra posição 0 assim que uma tecla é digitada.

No setter do text, faça isso:

  @override
  set text(String newText) {
  if (super.text != newText) {
  value = value.copyWith(
      text: newText,
      selection: TextSelection.collapsed(offset: (newText ?? '').length),
      composing: TextRange.empty);
    }
  }

Isso resolverá um bug que ocorre quando as vezes o cursor vai pra posição 0 assim que uma tecla é digitada.

O mesmo fix pode ser aplicado no updateValue.

String padding

Hello, let's suppose I have a mask 000.000-00 and the user types 1234. Is there a way to automatically show 000.012-34 in the field? I would need it to update as the user types.

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

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

Can I use this in Text()?

Hello,

A newbie here, please help.
Can I use this in Text()? How? Please see below code where I want to use this.

// Holds the text that user typed.
String text = '';

Container(
margin: const EdgeInsets.only(left: 86.0),
alignment: Alignment.centerLeft,
child: Text(
text,
style: TextStyle(
fontSize: 35.0,
letterSpacing: 20.0,
),
),
),

I want that when user types it only the * will appear and not the actual number that the user types.

Thanks in advance.

Is it possible to make part of the mask immutable ?

Hello 👋, thank you for this package! 😊
I try to create phone field.
And when user start writing form adding +7 (Russian International phone code).
I need to make +7 an immutable part. How can I do this ?
image 9 (1)

onChanged wrong value

onChanged wrong value

input: 0
input: 1

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

image

DefaultTabController problem flutter_masked_text

Good Morning,
I am using flutter masked text inside a DefaultTab Controller, after switching between Tabs three or four times, the following error is generated:

The following assertion was thrown building Container:
A MaskedTextController was used after being disposed.

Is there anything I'm doing wrong?

Version: flutter_masked_text: ^0.8.0

Follow the Flutter Doctor:

C:\src\flutter\bin\flutter.bat doctor --verbose
[√] Flutter (Channel stable, v1.9.1+hotfix.2, on Microsoft Windows [versão 10.0.18362.356], locale pt-BR)
• Flutter version 1.9.1+hotfix.2 at C:\src\flutter
• Framework revision 2d2a1ffec9 (12 days ago), 2019-09-06 18:39:49 -0700
• Engine revision b863200c37
• Dart version 2.5.0

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at C:\Users\cristian_regazzo\AppData\Local\Android\sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.2
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
• All Android licenses accepted.

[√] Android Studio (version 3.5)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 39.0.3
• Dart plugin version 191.8423
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)

[√] VS Code (version 1.38.0)
• VS Code at C:\Users\cristian_regazzo\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.4.1

[√] Connected device (1 available)
• Samsung Galaxy S9 • 192.168.247.104:5555 • android-x86 • Android 8.0.0 (API 26)

• No issues found!
Process finished with exit code 0

Tks,

Cristian Regazzo

Get text with no mask

It is do not possible to get the text with no mask, example:
var controller = new MaskedTextController(text: '', mask: '000-000');
controller.updateText('123456');
print(controller.text); //123-456

but if do you need the value like this ?:
print(controller.text); //123456

update mask blocking backspace on iOS

Hi guys, as the title says, I'm not being able to delete any character in the input field.

Here's the code:
doc.addListener(() { doc.updateMask( doc.text.length >= 15 ? '00.000.000/0000-00' : '000.000.000-000'); });

This problem only occurs on iOS simulator, I hadn't the chance to test it on a device yet. I even tried it on different versions of iOS simulator but nothing changed.

incorrect value from MoneyMaskedTextController

The .numberValue property (and .text for that matter) are giving me a value with the decimal in the wrong place (different from how it looks in my TextField).

Code used:

    var moneyController = MoneyMaskedTextController(
        decimalSeparator: '.',
        thousandSeparator: ',');
    moneyController.updateValue(65.99);

change value via TextField to 659.91

  moneyController.numberValue
  // returns  65.991

also:

  • It always seems to return 3 places after the decimal, not 2
  • Once the thousands placeholders appear, the TextField onchange event stops firing

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));
                        },
                      ),

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

[BUGFIX] Editing a character in the middle of the text (possible solution).

I was going through a problem when editing a value in a masked input. For example, if the user typed his phone "(54) 99999-9999" and wanted to change it to "(54) 94999-9999" the input would put the number 4 in the end of the text, like "(54) 99999-9994".

So, following the initial suggestion made by Marc in the #16 , i change the text method to this:

@override
set text(String newText) {
  print(newText);
  if (super.text != newText) {
    int position = this.selection.baseOffset >= super.text.length
        ? (newText ?? '').length
        : this.selection.baseOffset;
    value = value.copyWith(
        text: newText,
        selection: TextSelection.collapsed(offset: position),
        composing: TextRange.empty);
  }
}

Basically, I only put the cursor at the end of the text, if it was already at the end.

Hope it helps (:

MoneyMask force 0,000 (three 0 on decimal)

image

I will follow the order of the print numbering.

  1. MoneyMaskTextController declaration, in BRL format without "R$".
  2. What I typed in the Field
  3. What is printing on onChange
  4. Result of conversion from BRL to Double (to make an operation in the API)

Null safety?

Now that Flutter 2 is out, can we please migrate to null-safe?

Hi, I proposed this change for MoneyMaskedTextController for better UX

@flutter_masked_text.dart

double get numberValue {
    if (this.text == '') return 0;
    List<String> parts = [];
    if (this.text.length == 1 && this.text!=decimalSeparator && this.text!=thousandSeparator) {
      for (var i = 0; i < precision - this.text.length; i++) {
        parts.insert(parts.length, "0");
      }
      parts.insert(parts.length, this.text);
    } else
      parts = _getOnlyNumbers(this.text).split('').toList(growable: true);
    if (parts.length >= precision)
      parts.insert(parts.length - precision, decimalSeparator);
    return double.parse(parts.join());
  }

Improvements :

  • No more errors
  • When typing from empty value it will fix automagically
  • Using thousandSeparator and decimalSeparator variables

Thanks

onChanged wrong value

onChanged wrong value

typed: 0
typed: 1

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

image

Remove mask when deleting

Just started using this library and so far so good. The only thing I noticed is when typing the mask gets inserted automatically, I would infer that when deleting it would automatically remove the mask as well. Right now when deleting, you have to manually delete the mask one by one.

Number is reset to initial value on pressing the "Done" button

Similarly to the closed issue, I am having a problem when clicking on the "Done" button. The displayed value is reset to the initial value (0.00 in most cases) when using the MoneyMaskedTextController. I can reproduce this on iPhone 5 and Android simulated and on a Samsung s10. I've stripped all my logic out of the code and still the issue happens. Should you need more information, please feel free to check in.

This is my implementation of the issue (I have stripped out unnecessary containers, etc. but I have tested it and it does the same):

Widget _createCurrencyField(Field field) {
    final _currencyController = MoneyMaskedTextController(
        initialValue: 0.0,
        decimalSeparator: ',',
        thousandSeparator: '.',
        rightSymbol: '',
        leftSymbol: '€');

     return TextField(
            controller: _currencyController,
            keyboardType: TextInputType.number,
          );
  }

Flutter for web support

Hello

I'm using flutter_masked_text in my app and now I need to create a web version of some views and would be very nice if this package support Flutter Web :)

Are you thinking in add support for Flutter Web soon? This is in your plans?
Thanks!

Remove mask to do a Request IDEA

i'm start programing flutter 2 days ago, this is a cool project but if i need to remove the mask to do a request, the text is seted to ""

  static String maskCnpj = "00.000.000/0000-00";
  final _cnpj = MaskedTextController(mask: maskCnpj);
  final _user = TextEditingController();
  final _password = TextEditingController();
  void onClick() {
    print("potato");
    if (_formkey.currentState.validate()) {
      print(_cnpj.text); //out 12.345.678/9101-11
      print(_user.text);
      print(_password.text);
    }
  }

i try remove mask with .updateMask("") but this clean the field; ok : Im noob.
after the i remove the mask with .updateMask("00000000000000") <- THIS WORKS BUT is not cool

  static String maskCnpj = "00.000.000/0000-00";
  final _cnpj = MaskedTextController(mask: maskCnpj);
  final _user = TextEditingController();
  final _password = TextEditingController();
  void onClick() {
    print("potato");
    if (_formkey.currentState.validate()) {
      _cnpj.updateMask("00000000000000");
      print(_cnpj.text); 
      _cnpj.updateMask(maskCnpj);
      print(_user.text);
      print(_password.text);
    }
  }

maybe add a var.textNoMask will be awesome

tansk's for attention

Using default placeholder text

At times, you just want to see the default placeholder's text by setting initialValue to null, this blows up currently.

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

Hello,

I'm getting this error in my MoneyMaskedTextController with precision: 2.

Screenshot_2019-08-22-09-40-45-03

The error occurs when I go out of the TextField with less than 2 digits, for example: my mask is from Brazilian real R$ 0,00, if I type only 5 cents and go out of the TextFiel, I get this error.

For example:

Screenshot_2019-08-22-09-50-05-21

In this example, when I press the ritgh button, the error occurs.
My controller:

  MoneyMaskedTextController controller = new MoneyMaskedTextController(
      decimalSeparator: ',',
      thousandSeparator: '.',
      leftSymbol: 'R\$ ',
      precision: 2);

Debuging, the error appears occurs in this point on the "flutter_masked_text.dart":

  double get numberValue {
    List<String> parts = _getOnlyNumbers(this.text).split('').toList(growable: true);

    parts.insert(parts.length - precision, '.');

    return double.parse(parts.join());
  }

I think that is because the parts.length - precision = -1, so, the throw occurs

Thanks

Warning on change value

I'm getting this warnings on change value

W/IInputConnectionWrapper( 9729): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper( 9729): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper( 9729): getTextAfterCursor on inactive InputConnection

This is my code

import 'package:flutter/material.dart';
import 'package:flutter_masked_text/flutter_masked_text.dart';

class InputRealField extends StatelessWidget {
  final IconData icon;
  final String hint;
  final String label;
  final bool obscure;
  final bool enable;
  final Stream<double> stream;
  final Function(double) onChanged;
  final dynamic initialData;
  final MoneyMaskedTextController _controller = new MoneyMaskedTextController(
      decimalSeparator: ',',
      thousandSeparator: '.',
      leftSymbol: "R\$ ",
      precision: 2);
  final bool alwaysCursorInEnd;

  InputRealField(
      {Key key,
      this.icon,
      this.hint,
      this.obscure = false,
      this.enable = true,
      this.stream,
      this.label,
      this.onChanged,
      this.initialData,
      this.alwaysCursorInEnd = false})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    _controller.addListener(_onChangeValue);
    return StreamBuilder(
        stream: this.stream,
        initialData: initialData,
        builder: (context, snapshot) {
          _controller.updateValue(snapshot.data);
          if (alwaysCursorInEnd) {
            _controller.selection = new TextSelection(
                baseOffset: _controller.value.text.length,
                extentOffset: _controller.value.text.length);
          }
          return TextField(
            enabled: this.enable,
            enableInteractiveSelection: false,
            autofocus: false,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
                labelText: this.label,
                hintText: this.hint,
                errorText: snapshot.hasError ? snapshot.error : null),
            obscureText: this.obscure,
            controller: _controller,
          );
        });
  }

  void _onChangeValue() {
    onChanged(_controller.numberValue);
  }
}

IP Address

Hi, I would like to mask IP Address in TextFormField. The following code is partially written and does not work. Please advice.

final controller = new MaskedTextController(mask: '#.#.#.#',
    translator: {
      '#': new RegExp(r'^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$')
    }); 
...

For each value, the number should be between 0-255.

Problem with cursor

When I type anything the cursor moves to beggining of the text filed after some time which doesn't happens when I use texteditingcontroller. It only happens with maskedcontroller. Please fix this issue as soon as possible it's very irritating.
Flutter gives an error:- “Text selection index was clamped (-1->0) to remain in bounds this may not be your fault as some key boards.......". Please fix this at immediate because I need it or help me solve in any other way.

Update Mask moves cursor

I have a listener into a MaskedTextController where I update the mask based on the number of characters.

Something like this:

if (_phoneNumberController.text.length == 15) {
  _phoneNumberController.updateMask('(00) 00000-0000');
} else {
  _phoneNumberController.updateMask('(00) 0000-00000');
}

The problem is, when updating the mask, the text field cursor goes to the text field start. Is this the expected behaviour? If so, are there any workarounds?

Thanks in advance!

RangeError was thrown while dispatching notifications for MoneyMaskedTextController

I am getting this exception when the MoneyMaskedTextController is set to blank ("")

flutter --version
Flutter 1.20.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision bbfbf1770c (11 days ago) • 2020-08-13 08:33:09 -0700
Engine • revision 9d5b21729f
Tools • Dart 2.9.1

flutter_masked_text: 0.8.0

Here is the initializer
_myMoneyField = MoneyMaskedTextController(
decimalSeparator: ',',
thousandSeparator: '.',
precision: 3,
initialValue: 1);

══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
The following RangeError was thrown while dispatching notifications for MoneyMaskedTextController:
Invalid value: Only valid value is 0: -2
When the exception was thrown, this was the stack:

(elided 3 frames from dart:async)
The MoneyMaskedTextController sending notification was:
MoneyMaskedTextController#6f686(TextEditingValue(text: ┤├, selection: TextSelection(baseOffset:
-1, extentOffset: -1, affinity: TextAffinity.downstream, isDirectional: false), composing:
TextRange(start: -1, end: -1)))

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?

optional character translator

Currently, the library has the following translators.

return {
      'A': new RegExp(r'[A-Za-z]'),
      '0': new RegExp(r'[0-9]'),
      '@': new RegExp(r'[A-Za-z0-9]'),
      '*': new RegExp(r'.*')
};

It would be great to have a translator for optional things. like:

'a' = similar to 'A' but will be optional.
'1' = similar to '0' but will be optional.
'<' = similar to '@' but will be optional.
'>' = simlilar to '*' but will be optional.

For e.g:

if the mask is '11-1' then it can accept the following inputs:

9
9-9
99
99-9

I already tried to use the translator but it is not working:

_accountCtrl =
        MaskedTextController(mask: '**-*', translator: {
      '*': RegExp(r'([0-9]*)'),
    });

TextFormField value disappears when next field is tapped

Hi

I'm attempting to use this library to mask some of my TextFormField fields. However, when I add the controller attribute using the MaskedTextController, whenever I tap on the next field or exit the field I'm editing by any way, the TextFormField value is cleaned.

I've checked issues #13 and #28 but neither helped me.

Dependency:

  flutter_masked_text: ^0.8.0

This is my code:

class _SignupInfoStepState extends State<SignupInfoStep> {
  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final MaskedTextController cpfController = MaskedTextController(mask: '000.000.000-00', text: widget.form.cpf);
    cpfController.afterChange = (String previous, String next) {
      cpfController.updateText(next);
    };

    return SingleChildScrollView(
      child: Form(
        key: formKey,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: <Widget>[
              if (widget.form.complete) ...[
                TextFormField(
                  decoration: InputDecoration(
                    labelText: 'CPF',
                    border: OutlineInputBorder(),
                  ),
                  style: TextStyle(fontSize: 20),
                  initialValue: widget.form.cpf,
                  validator: (cpf) {
                    if (cpf == null || cpf.isEmpty) {
                      return 'Campo obrigatório';
                    }
                    if (!CPFValidator.isValid(cpf)) {
                      return 'CPF inválido';
                    }
                    return null;
                  },
                  keyboardType: TextInputType.number,
                  onSaved: (cpf) {
                    setState(() => widget.form.cpf = cpf);
                  },
                  maxLength: 14,
                  controller: cpfController,
                ),
            ],
          ),
        ),
      ),
    );
  }
}

flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.9.1+hotfix.6, on Mac OS X 10.15.1 19B88, locale
    en-US)
 
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.1)
[✓] Xcode - develop for iOS and macOS (Xcode 11.2.1)
[✓] Android Studio (version 3.5)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.3)
[!] Connected device
    ! No devices available

! Doctor found issues in 1 category.

Problem with MoneyMaskedTextController cursor

Hi, I've got a problem below :

ezgif com-resize (1)

The cursor always seem to move to the start of the textfield. Is there any solution to this? Cause this happens to give user a bad experience when filling in the form.

My code that related to this :

final _priceController = MoneyMaskedTextController(
    precision: 0, 
    decimalSeparator: '', 
    thousandSeparator: ',',
  );

Awaiting your response, sir

Long press on backspace delete whole mask

  • When you only tap backspace you can't delete the mask, you only can delete the user input until its 0 again.
    (In my expample '€ 0,00')
  • But when you don't tap and instead touch & hold, the TextInputField goes blank.

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!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.