1
1
import 'package:flutter/material.dart' ;
2
2
import 'package:flutter/scheduler.dart' ;
3
- import 'package:flutter/services.dart' ;
4
3
import 'package:flutter_form_builder/flutter_form_builder.dart' ;
5
4
6
5
class FormBuilderField <T > extends FormField <T > {
@@ -71,9 +70,11 @@ class FormBuilderFieldState<T> extends FormFieldState<T> {
71
70
72
71
T _initialValue;
73
72
74
- FocusNode _node ;
73
+ FocusNode _focusNode ;
75
74
76
- bool _focused = false ;
75
+ FocusNode get _effectiveFocusNode =>
76
+ widget.focusNode ??
77
+ (_focusNode ?? = FocusNode (debugLabel: '${widget .attribute }' ));
77
78
78
79
@override
79
80
void initState () {
@@ -86,31 +87,9 @@ class FormBuilderFieldState<T> extends FormFieldState<T> {
86
87
false )
87
88
? _formBuilderState.initialValue[widget.attribute]
88
89
: null );
89
- _node = widget.focusNode ?? FocusNode (debugLabel: '${widget .attribute }' );
90
- _node.addListener (_handleFocusChange);
91
- _node.attach (context, onKey: _handleKeyPress);
92
90
setValue (_initialValue);
93
91
}
94
92
95
- void _handleFocusChange () {
96
- if (_node.hasFocus != _focused) {
97
- setState (() {
98
- _focused = _node.hasFocus;
99
- });
100
- }
101
- }
102
-
103
- bool _handleKeyPress (FocusNode node, RawKeyEvent event) {
104
- if (event is RawKeyDownEvent ) {
105
- print ('Focus node ${node .debugLabel } got key event: ${event .logicalKey }' );
106
- if (event.logicalKey == LogicalKeyboardKey .tab) {
107
- FocusScope .of (context).nextFocus ();
108
- return true ;
109
- }
110
- }
111
- return false ;
112
- }
113
-
114
93
@override
115
94
void save () {
116
95
super .save ();
@@ -130,7 +109,7 @@ class FormBuilderFieldState<T> extends FormFieldState<T> {
130
109
@override
131
110
void reset () {
132
111
super .reset ();
133
- setValue (_initialValue );
112
+ setValue (initialValue );
134
113
widget.onReset? .call ();
135
114
}
136
115
@@ -140,15 +119,14 @@ class FormBuilderFieldState<T> extends FormFieldState<T> {
140
119
}
141
120
142
121
void requestFocus () {
143
- FocusScope .of (context).requestFocus (_node );
122
+ FocusScope .of (context).requestFocus (_effectiveFocusNode );
144
123
}
145
124
146
125
@override
147
126
void dispose () {
148
127
_formBuilderState? .unregisterFieldKey (widget.attribute);
149
- _node.removeListener (_handleFocusChange);
150
128
// The attachment will automatically be detached in dispose().
151
- _node .dispose ();
129
+ _focusNode ? .dispose ();
152
130
super .dispose ();
153
131
}
154
132
}
0 commit comments