如何创建继承 TextField 小部件的类并覆盖 OnChanged 事件?
当用户打字时,我需要在我的应用程序中重置全局计时器,我想在自定义小部件中执行此操作并通过应用程序使用它。
类似的东西
@override
OnChanged() {
resetTimer();
if (!widget.OnChanged) {//call OnChanged if is set}
}
为了能够将我的自定义行为添加到 OnChanged,我必须在我的自定义小部件上“公开”祖先事件。它正在工作,我可以继续创建文本编辑,而无需在每个实例中将计时器调用添加到 OnChanged。
class CustomTextField extends TextField {
const CustomTextField({
Key? key,
TextEditingController? controller,
InputDecoration decoration = const InputDecoration(),
TextInputType? keyboardType,
TextAlign textAlign = TextAlign.start,
List<TextInputFormatter>? inputFormatters,
GestureTapCallback? onTap,
ValueChanged<String>? onChanged,
}) : super(
key: key,
controller: controller,
decoration: decoration,
keyboardType: keyboardType,
inputFormatters: inputFormatters,
textAlign: textAlign,
onTap: onTap,
onChanged: onChanged,
);
@override
State<CustomTextField> createState() => _CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
@override
Widget build(BuildContext context) {
return TextField(
controller: widget.controller,
decoration: widget.decoration,
keyboardType: widget.keyboardType,
inputFormatters: widget.inputFormatters,
textAlign: widget.textAlign,
onTap: widget.onTap,
onChanged: _handleTextChanged,
);
}
void _handleTextChanged(String value) {
startSessionTimer(); //my call to the timer :)
if (widget.onChanged != null) {
widget.onChanged;
}
}
}