Flutter TextFormField with non-const decoration - flutter

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?

Related

if (value.isEmpty) isEmpty is not working how i fix this

I tried to fix using ?. and !. and !! none of them is working
And error message is The property 'isEmpty' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').
return TextFormField(
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value.**isEmpty**) {
setState(() {
errors.add("Please enter your email");
});
}
return null;
},
decoration: const InputDecoration(
labelText: "Email",
hintText: "Enter your email",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(
svgIcon: "assets/icons/Mail.svg",
),
),
);
}
}
If you call
if(value.isEmpty)
and value is null, what condition will be checked?
Try
if(value != null && value.isEmpty)
Or see: https://stackoverflow.com/a/52948927/5619109
if(value?.isEmpty ?? true)
I recommend to use Flutter Form
Create a function like this, customize it for yourself, just like above.
String? _validateInput(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
}
Then use this function to validate, like
return TextFormField(
keyboardType: TextInputType.emailAddress,
validator: _validateInput,
decoration: const InputDecoration(
labelText: "Email",
hintText: "Enter your email",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(
svgIcon: "assets/icons/Mail.svg",
),
),
);
}
}
Try this it's work for me
value == null || value.isEmpty
Or
value!.isEmpty

flutter format currency in texformfield

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->

How to validate email in a TextFormField

There is a way to validate the input of the user with a TextFormField or TextField,to reject the input if it's not an email.
You can use regex for this
Form and TextFormField like so
Form(
autovalidateMode: AutovalidateMode.always,
child: TextFormField(
validator: validateEmail,
),
)
then the validation function
String? validateEmail(String? value) {
const pattern = r"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'"
r'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-'
r'\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*'
r'[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4]'
r'[0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9]'
r'[0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\'
r'x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])';
final regex = RegExp(pattern);
return value!.isNotEmpty && !regex.hasMatch(value)
? 'Enter a valid email address'
: null;
}
Link to regex https://stackoverflow.com/a/201378/12695188
To validate the form, you can use the autovalidate flag and set up a validator for email. There are many options, including regex or manually writing your own checker, but there are also packages available which implement email checking already.
For example, https://pub.dev/packages/email_validator.
To use it, add it to your pubspec:
dependencies:
email_validator: '^1.0.0'
import 'package:email_validator/email_validator.dart';
...
Form(
autovalidate: true,
child: TextFormField(
validator: (value) => EmailValidator.validate(value) ? null : "Please enter a valid email",
),
)
There are many other validation packages, some of which support may different types of validation. See this search for more https://pub.dev/packages?q=email+validation.
TextFormField(
validator: (val) => val.isEmpty || !val.contains("#")
? "enter a valid eamil"
: null,
decoration: InputDecoration(hintText: 'email'),
),
In the validator first we are checking if the formfeild is empty and also we are checking if the text entered dose not contains "#" in it . If those conditions are true then we are returning a text "enter a valid email" or else we are not returning anything
I suggest use of this excellent library called validators
Add dependency to your package's pubspec.yaml file:
dependencies:
validators: ^2.0.0 # change to latest version
Run from the command line:
$ pub get
// on VSCode u need not do anything.
Import in your Dart code:
import 'package:validators/validators.dart';
Validate your field
Form(
child: TextFormField(
validator: (val) => !isEmail(val) ? "Invalid Email" : null;,
),
)
QUICK FIX 🙂
Use this in your TextFormField.
validator: (value) {
if(value == null || value.isEmpty || !value.contains('#') || !value.contains('.')){
return 'Invalid Email';
}
return null;
},
The previous answers all discuss options for verifying a TextFormField in a Form. The question asks about doing this in
TextFormField or TextField
TextField does not support the validator: named parameter but you can use any of the previously mentioned techniques to check the validity of the email every time the user modifies the email address text. Here is a simple example:
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
setState(() {
_email = value;
_emailOk = EmailValidator.validate(_email);
});
},
decoration:
kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
),
You can use the validation result as you see fit. One possibility is to keep a login button deactivated until a valid email address has been entered:
ElevatedButton(
child: Text('Log In'),
// button is disabled until something has been entered in both fields.
onPressed: (_passwordOk && _emailOk) ? ()=> _logInPressed() : null,
),
If you use flutter_form_builder with flutter_builder_validators
email verification can be done easily
FormBuilderTextField(
name: 'email',
decoration: InputDecoration(
labelText: 'Email',
errorText: _emailError,
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.required(),
FormBuilderValidators.email(),
]),
),
TextFormField(
validator: (value) {
if(value.isEmpty) {
return "Please enter email";
} else if(!value.contains("#")) {
return "Please enter valid email";
}
},
decoration: InputDecoration(hintText: 'email'),
),
No need to use external libraries or Regex!
Put your text field inside a form, set autovalidate to 'always' and inside TextFormField add a validator function:
Form(
autovalidateMode: AutovalidateMode.always,
child: TextFormField(
validator: validateEmail,
),
)
Validator function:
String? validateEmail(String? value) {
if (value != null) {
if (value.length > 5 && value.contains('#') && value.endsWith('.com')) {
return null;
}
return 'Enter a Valid Email Address';
}
note: length > 5 because '.com' and '#' make 5 characters.

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.