How to set the value to a TextFormField in flutter - 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')

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 change color on TextFormField validator: (value) => validateCharacters(value),

I want to change this color to grey But but its red How can I achieve that or is it possible or not?
code:
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
//Want to change color HERE
validator: (value) => validateCharacters(value),
inputFormatters: [
LengthLimitingTextInputFormatter(20),
],
},
),
String? validateCharacters(String? value) {
String pattern = (r'^(?=.*?)(?=.*?[a-z])(?=.*?[20]).{20,}$');
RegExp regex = RegExp(pattern);
if (value == null || value.isEmpty || !regex.hasMatch(value)) {
return 'note: `Only 20 characters allow`'; //Want this to be grey color
} else {
return null;
}
}
You can add a error style inside decoration.
Check this:
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) => validateCharacters(value),
decoration: InputDecoration(
errorStyle: TextStyle(color: Colors.grey)
),
inputFormatters: [
LengthLimitingTextInputFormatter(20),
],
},
),
If we want to change validation text color then put in to the decoration property in error style according to your UI.
TextFormField( autovalidateMode: AutovalidateMode.onUserInteraction, validator: (value) => validateCharacters(value), decoration: enter code hereInputDecoration(errorStyle: TextStyle(color: Colors.grey)),)
`
You have to use
decoration: InputDecoration(
errorStyle: TextStyle(color: Colors.red)
),
in your TextFormField

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

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.