在 Flutter 中将 inputDecorationTheme 转换为 InputDecoration

Kos*_*lav 3 dart flutter

我正在编写一个FormBuilderField扩展,它可以从 main 中获取所有装饰属性,ThemeObjecthintText我希望能够手动传递的属性除外。

从我的角度来看,主要问题如下:themeObject仅包含InputDecorationTheme没有属性的实例,因此我决定通过将实例转换为来hintText创建,然后使用方法注入缺少的属性。您可以查看下面的代码示例。InputDecorationInputDecorationThemeInputDecorationcopyWith

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
 )
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误是“预期为‘InputDecoration’类型的值,但得到了‘InputDecorationTheme’类型之一......”。我理解这个错误,所以我想知道是否有一种方法可以InputDecoration从一个实例中获取 的实例InputDecorationTheme并向其添加自定义属性?

很高兴听到任何建议。

Spe*_*ion 8

我相信实例化时InputDecoration它会自动继承InputDecorationTheme. 如果不是这种情况,那么您可以使用applyDefaults方法将InputDecoration属性应用InputDecorationTheme到您的InputDecoration对象。

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,
);
Run Code Online (Sandbox Code Playgroud)

在你的情况下,它将是:

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

  ...
}
Run Code Online (Sandbox Code Playgroud)