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?
CodePudding user response:
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?