bhrott / flutter-masked-text Goto Github PK
View Code? Open in Web Editor NEWA masked text for Flutter.
Home Page: https://pub.dartlang.org/packages/flutter_masked_text
License: MIT License
A masked text for Flutter.
Home Page: https://pub.dartlang.org/packages/flutter_masked_text
License: MIT License
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());
}
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);
};
Great job on this library!
Would love to see e-mail formatter as well.
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.
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.
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.
Hi,
How can I remove the default 0 value for MoneyMaskedTextController form 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
For example -
mask: (000) 000-0000
value: (123) 456-7890
unmaskedValue: 123456789
??
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.
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
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"
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
The '-' symbol is not showing up in the TextField when the value is negative. Is this intended?
For example:
value: -1234.00
TextField render: 1234.00
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.
Ex : 22000
I Want just 22.000 Not 22.000,00
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:
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));
},
),
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
Error trying to retrieve the package. Any ideas?
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 (:
Now that Flutter 2 is out, can we please migrate to null-safe?
@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 :
Thanks
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.
I'd like to have the CPF and CNPJ validator working on that package if it's possible, thanks!
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,
);
}
I just want to convert 20000 to 20.000 not 20.000,00. Thank you 🙏
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!
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
At times, you just want to see the default placeholder's text by setting initialValue to null, this blows up currently.
Hello,
I'm getting this error in my MoneyMaskedTextController with precision: 2.
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:
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
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);
}
}
The function updateText crashes when a null variable is taken as text parameter.
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.
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.
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!
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)))
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?
It would be nice to add a property to the MoneyMaskedTextController which enables or disables the ability to input negative numbers
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]*)'),
});
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.
Hi, I've got a problem below :
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
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!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.