0

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?

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Chris Nadovich
  • 202
  • 1
  • 7
  • 1
    Just delete the `const` modifier. You can't make inputdecoration constant when it has a variable in it. – GrahamD Jan 22 '23 at 16:44
  • Doh! That'll teach me to cut/paste without reading carefully. Thanks! – Chris Nadovich Jan 22 '23 at 19:29
  • If you start using a linter eg. https://pub.dev/packages/lint it will flag many of these kind of code errors. Warning though, you will probably get a lot of warnings to fix the first time you use it – GrahamD Jan 22 '23 at 20:04
  • Thanks for the tip about lint. The problem, of course, is I'm new to Flutter. When I see "const" in an example I assume it's there for a mandatory reason, not that somebody was trying to optimize the declaration for that very specific case where const would be possible. So when the code won't compile because const is present, my first instinct isn't to "just delete the offending keyword". Also I come from a perl/php background where everything is ridiculously mutable. I assume people wouldn't declare something const unless there's no alternative. But I'm learning. Thanks again. – Chris Nadovich Jan 25 '23 at 22:05

1 Answers1

1

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?

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56