flutter format currency in texformfield - flutter

I have a flutter app which accepts an amount of money as input using a textformfield. I would like to format the input in textformfield so that whatever is being input can be formatted as currency copmlete wiht thousand separator commas. I have tried using the intl package number formatter but all I can do is print it to the command line.
Here is how it looks currently
This is how I would like it to look like
This is the textfield code
TextEditingController currencyControler = TextEditingController();
String? amount;
TextFormField(
controller: currencyControler,
keyboardType: TextInputType.number,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter an amount';
}
return null;
},
onSaved: (String? value) {
amount = value;
},
decoration: InputDecoration(
icon: const Icon(Icons.money_outlined),
labelText: "Amount",
hintText: 'Enter an amount',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
),
),
)
How can I format the input so that the comma separators appear as any number is being entered

Try below code hope its helpful to you.Used intl package here for number formation
Your functions:
TextEditingController currencyControler = TextEditingController();
String formNum(String s) {
return NumberFormat.decimalPattern().format(
int.parse(s),
);
}
Your Widget:
TextFormField(
controller: currencyControler,
decoration: InputDecoration(
border: OutlineInputBorder(),
prefixIcon: Icon(
Icons.money,
)),
keyboardType: TextInputType.number,
onChanged: (string) {
string = '${formNum(
string.replaceAll(',', ''),
)}';
currencyControler.value = TextEditingValue(
text: string,
selection: TextSelection.collapsed(
offset: string.length,
),
);
},
),
Your result screen->

Related

Flutter TextFormField with non-const decoration

I want to write something like a function that generates TextFormFields with different names, but I don't want the labelText attribute to be const. That way I can easily rubber stamp out a bunch of similar fields that have different names.
For example
TextFormField myFormField(myMapType myMap, String fieldName) {
return TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: fieldName,
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your $fieldName';
}
return null;
},
initialValue: myMap.attribute[fieldName],
onSaved: (val) {
setState(
() {
myMap.setAttribute(fieldName, val!);
},
);
});
}
But that gives an error "Invalid constant value" at the line "labelText: fieldName". What's the trick needed to accomplish what I'm trying to do? Or what dumb mistake did I make?
fieldName will get on runtime rather than compile time. Therefore you cant use const
You can do
return TextFormField(
decoration: InputDecoration(
border: const OutlineInputBorder(), //this can be const
labelText: fieldName,
),
validator: (value) {
You can check What is the difference between the "const" and "final" keywords in Dart?

How to restrict user from entering leading spaces and imojis in name field

I have name field in profile page. I want to restrict user from adding leading spaces. But in the process what I did is the user can't put any space now. I want him to simple enter "Arjun Malhotra" and not " space space space Arjun Malhotra"......
This is the code
child: TextFormField(
inputFormatters: [
FilteringTextInputFormatter
.deny(
RegExp('[ ]')),
],
maxLength: 20,
readOnly: !edit,
controller: name,
autovalidateMode:
AutovalidateMode
.onUserInteraction,
autofocus: true,
validator: (value) {
RegExp regex =
RegExp(r'^.{3,}$');
if (value!.isEmpty) {
return ("Name can't be empty");
}
if (!regex
.hasMatch(value)) {
return ("Name can't be empty");
}
if (value.trim() ==
"") {
return ("Name can't be empty");
}
if (value
.trim()
.length <=
2) {
return ("Minimum of 3 characters Required");
}
return null;
},
onSaved: (value) {
name.text = value!;
},
onChanged: (value) {
context
.read<
ProfileDetails>()
.name = value;
},
decoration:
InputDecoration(
counterText: "",
filled: true,
fillColor: const Color(
0xFFC2E3FE),
enabledBorder:
InputBorders
.enabled,
errorBorder:
InputBorders.error,
focusedErrorBorder:
InputBorders.error,
border:
InputBorder.none,
focusedBorder:
InputBorders
.focused,
contentPadding:
const EdgeInsets
.only(
left: 30,
right: 10),
hintText: "Name",
),
),
Above code only allows this format "ArjunMalhotra". How can I achieve what I want and also I dont want user to add emojis. Is there a special keyboard type I need to specify or what?
^\s*: This will match any (*) whitespace (\s) at the beginning (^) of the text
inputFormatters: [
FilteringTextInputFormatter.deny(RegExp(r'^\s*')),
],

How do I use the credit card date format mm/yy in FLUTTER

child: new TextFormField(
maxLength:5,
controller:
TextEditingController(text: donation.date),
onChanged: (value) {
donation.date = value;
},
decoration: InputDecoration(
suffixText: '',
suffixStyle: TextStyle(
color: Color(0xffde0486),
),
labelText: 'Expiry Date',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
style: TextStyle(color: Colors.white),
autofocus: true,
),
I have this piece of code for a credit card that I am implementing in Flutter. I want to put the mm/yy format on the textfield. When the user has entered the month, the text field should automatically show the '/'. How do I do this?
You can achieve your result using the onChange method. You can check the length of the input and insert a '/' into the text if it is 2 i.e. dd
You need to store the controller in a seperate variable, because we want to use it later for inserting '/':
var _controller = new TextEditingController(text: donation.date);
Add this _controller and onChange callback to your TextFormField:
TextFormField(
controller: _controller, //<-- Add controller here
onChanged: (value) {
if(value.length == 2) _controller.text += "/"; //<-- Automatically show a '/' after dd
donation.date = value;
},
...
),
Yo can try this package flutter_multi_formatter to format the Expiration Date field as well as the credit card number field.
Update !
I just found a package: flutter_masked_text2 that can help you solve the problem!
var controller = new MaskedTextController(mask: '00/00');

How to set the value to a TextFormField in flutter

I am trying to set a value to the TextFormField in flutter.
But I couldn't find a way to do that.
this is how my widget looks like:
Widget _showHeadlineField() {
return TextFormField(
textInputAction: TextInputAction.next,
onEditingComplete: () {
FocusScope.of(context).requestFocus(_descriptionNode);
},
controller: _headlineController,
validator: (headline) {
if (headline == null || headline.isEmpty) {
return "Headline cannot be empty";
}
},
decoration: InputDecoration(
labelText: "Headline",
hintText: "Covid-19 new stats",
border: OutlineInputBorder(),
icon: Icon(Icons.add_box),
),
);
}
I even tried initialValue but doesn't work. Can someone help me?
You can use
_headlineController.text = 'Your text';
Or when you create controller :
_headlineController = TextEditingController(text: 'Your text')

Insert prefix text into database in flutter

can I insert prefix text into the database? prefix text like this:
I think prefix text (+62) entered the database when it was submitted but no ... is there another way to have +62 auto in TextFormField and can it enter the database ??
and this is my code `
TextFormField(
controller: controllerPhone,
decoration: InputDecoration(
labelText: "Phone",
icon: Icon(Icons.phone),
prefixText: '+62',
),
validator: validatePhoneNumber,
onSaved: (String value) {
phone = value;
}, ),
`
Make the prefix a variable and concatenate it in your onSaved():
String _prefix = '+62'; // somewhere in your code
TextFormField(
controller: controllerPhone,
decoration: InputDecoration(
labelText: "Phone",
icon: Icon(Icons.phone),
prefixText: _prefix,
),
validator: validatePhoneNumber,
onSaved: (String value) {
phone = '$_prefix $value';
},
Let me know how this works out for you.