unfocus textfield when tapped outside

This commit is contained in:
Vadim 2025-03-28 09:34:32 +01:00
parent f0110e0edf
commit 7d42f1eb2c

View file

@ -1,27 +1,61 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class LightmeterTextField extends TextFormField { class LightmeterTextField extends StatefulWidget {
LightmeterTextField({ const LightmeterTextField({
super.controller, this.autofocus = false,
super.autofocus, this.controller,
super.initialValue, this.hintText,
super.inputFormatters, this.initialValue,
super.maxLength, this.inputFormatters,
super.onChanged, this.leading,
super.style, this.maxLength,
super.textAlign, this.onChanged,
Widget? leading, this.style,
String? hintText, this.textAlign = TextAlign.start,
}) : super( });
final bool autofocus;
final TextEditingController? controller;
final String? hintText;
final String? initialValue;
final List<TextInputFormatter>? inputFormatters;
final Widget? leading;
final int? maxLength;
final void Function(String)? onChanged;
final TextStyle? style;
final TextAlign textAlign;
@override
State<LightmeterTextField> createState() => _LightmeterTextFieldState();
}
class _LightmeterTextFieldState extends State<LightmeterTextField> {
late final focusNode = FocusNode(debugLabel: widget.hintText);
@override
Widget build(BuildContext context) {
return TextFormField(
autofocus: widget.autofocus,
autovalidateMode: AutovalidateMode.onUserInteraction, autovalidateMode: AutovalidateMode.onUserInteraction,
maxLines: 1, controller: widget.controller,
focusNode: focusNode,
initialValue: widget.initialValue,
inputFormatters: widget.inputFormatters,
maxLength: widget.maxLength,
onChanged: widget.onChanged,
style: widget.style,
textAlign: widget.textAlign,
decoration: InputDecoration( decoration: InputDecoration(
counter: const SizedBox(), counter: const SizedBox(),
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
errorStyle: const TextStyle(fontSize: 0), errorStyle: const TextStyle(fontSize: 0),
icon: leading, icon: widget.leading,
hintText: hintText, hintText: widget.hintText,
), ),
onTapOutside: (event) {
focusNode.unfocus();
},
validator: (value) { validator: (value) {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return ''; return '';
@ -30,4 +64,11 @@ class LightmeterTextField extends TextFormField {
} }
}, },
); );
}
@override
void dispose() {
focusNode.dispose();
super.dispose();
}
} }