我想在不同的表单中重用不同类型的字段,并且我创建了一个返回 TextFormField
的单独小部件。
从逻辑上讲,不同类型的字段有自己的验证和其他属性,因此我开始研究继承等以避免重写相同的代码块。
据我所知,Flutter 不鼓励继承 widget,所以我的问题是在 flutter 中重用各种表单字段的代码以保持可读性并保持代码整洁的最佳实践。
有什么建议吗?
最佳答案
根据我的经验,除了 flutter 提供的原始表单字段之外,我很少需要使用其他小部件。我发现重用每个字段的验证函数很有用,因为它们在验证方面通常有共同的需求。
这些只是两个基本示例。每当需要时,我都会将它们传递给表单字段的 validator
参数。
String? validatorForMissingFields(String? input) {
if (input == null || input.isEmpty || input.trim().isEmpty) {
return "Mandatory field";
}
return null;
}
String? validatorForMissingFieldsAndLength(String? input, int length) {
if (input == null || input.isEmpty || input.trim().isEmpty) {
return "Mandatory field";
}
if (input.length != length) {
return 'Not long enough';
}
return null;
}
无论如何,我更喜欢创建一个新的窗口小部件,其中包含具有一些固定属性和其他可自定义属性的基本窗口小部件,而不是扩展基本窗口小部件。这个例子不涉及表单字段,但我认为它更能说明我的观点。
///if text is not null, icon is ignored
class RectButton extends StatelessWidget {
final Function()? onPressed;
final String? text;
final IconData? icon;
final Color color;
const RectButton({this.text, this.icon, required this.onPressed, Key? key, this.color = mainLightColor}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(12.0),
child: OutlinedButton(
style: ButtonStyle(
side: MaterialStateProperty.all(BorderSide(color: color)),
overlayColor: MaterialStateColor.resolveWith((states) => color.withOpacity(0.5)),
backgroundColor: MaterialStateColor.resolveWith((states) => color.withOpacity(0.3)),
),
onPressed: onPressed,
child: text != null
? Text(
text!,
style: TextStyle(fontWeight: FontWeight.bold, color: color),
)
: Icon(
icon,
color: color,
)),
);
}
}
为了在所有应用程序中保持相同的外观和感觉,我创建了一个自定义按钮,上面有一些“不可见”小部件,使我可以设置一些属性,而无需扩展基本小部件。我需要自定义的属性被传递给构造函数。
关于Flutter:FormFields 的良好实践。我是否为每种类型的字段创建一个小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70679083/