Convert inputDecorationTheme to InputDecoration in Flutter

Viewed 346

I am writing a FormBuilderField extension that gets all of its decoration properties out of main ThemeObject except for hintText property which I want to be able to pass manually.

The main problem, from my point of you, is the following: the themeObject contains only InputDecorationTheme's instance which doesn't have hintText property, so I decide to create InputDecoration by casting InputDecorationTheme's instance to InputDecoration and then use copyWith method to inject the missing property. You can see the code sample below.

class MyNewAwsomeField extends FormBuilderField<String>{
# code that gets the theme object out of context (with is working fine)
static final theme = getThemeData();

MyNewAwsomeField ({
   Key? key,
   required String name,
   required String hintText,
   ValueChanged<String?>? onChanged,
}) : super(
   key:key,
   decoration: (theme.inputDecorationTheme as InputDecoration).copyWith(
   hintText: hintText,
   onChange: onChange,
   name:name
 )
}

The error I get says literary "Expected a value of type 'InputDecoration', but got one of type 'InputDecorationTheme' ...". I understand the error, so I would like to know is there a way to get InputDecoration's instance out of InputDecorationTheme one and add to it a custom properties?

Would glad to hear any piece advice.

1 Answers

I believe when instantiating InputDecoration it will automatically inherit all properties from InputDecorationTheme. If that's not the case then you can use applyDefaults method from InputDecoration to apply properties from InputDecorationTheme to your InputDecoration object.

const decoration = InputDecoration();

final decorationWithThemeProperties = decoration.applyDefaults(const InputDecorationTheme(
  filled: true,
  fillColor: Colors.red,
));
// or
// final decorationWithThemeProperties = decoration.applyDefaults(Theme.of(context).inputDecorationTheme);

return TextField(
  decoration: decorationWithThemeProperties,
);

In your case it would be:

class MyNewAwsomeField extends FormBuilderField<String>{
  // code that gets the theme object out of context (with is working fine)
  static final theme = getThemeData();

  MyNewAwsomeField ({
    Key? key,
    required String name,
    required String hintText,
    ValueChanged<String?>? onChanged,
  }) : super(
    key:key,
    decoration: (const InputDecoration()).applyDefaults(theme.inputDecorationTheme).copyWith(
      hintText: hintText,
      onChange: onChange,
      name: name
    )
  }

  ...
}
Related