-
-
Notifications
You must be signed in to change notification settings - Fork 562
Expand file tree
/
Copy pathform_builder_field.dart
More file actions
316 lines (272 loc) · 9.6 KB
/
form_builder_field.dart
File metadata and controls
316 lines (272 loc) · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import 'package:flutter/widgets.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
enum OptionsOrientation { horizontal, vertical, wrap, auto }
enum ControlAffinity { leading, trailing }
typedef ValueTransformer<T> = dynamic Function(T value);
/// A single form field.
///
/// This widget maintains the current state of the form field, so that updates
/// and validation errors are visually reflected in the UI.
class FormBuilderField<T> extends FormField<T> {
/// Used to reference the field within the form, or to reference form data
/// after the form is submitted.
final String name;
/// Called just before field value is saved. Used to massage data just before
/// committing the value.
///
/// This sample shows how to convert age in a [FormBuilderTextField] to number
/// so that the final value is numeric instead of a String
///
/// ```dart
/// FormBuilderTextField(
/// name: 'age',
/// decoration: InputDecoration(labelText: 'Age'),
/// valueTransformer: (text) => num.tryParse(text),
/// validator: FormBuilderValidators.numeric(context),
/// initialValue: '18',
/// keyboardType: TextInputType.number,
/// ),
/// ```
final ValueTransformer<T?>? valueTransformer;
/// Called when the field value is changed.
final ValueChanged<T?>? onChanged;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// Creates a single form field.
const FormBuilderField({
super.key,
super.onSaved,
super.initialValue,
super.autovalidateMode,
super.enabled = true,
super.validator,
super.restorationId,
required super.builder,
super.errorBuilder,
super.onReset,
super.forceErrorText,
required this.name,
this.valueTransformer,
this.onChanged,
this.focusNode,
});
@override
FormBuilderFieldState<FormBuilderField<T>, T> createState() =>
FormBuilderFieldState<FormBuilderField<T>, T>();
}
class FormBuilderFieldState<F extends FormBuilderField<T>, T>
extends FormFieldState<T> {
String? _customErrorText;
FormBuilderState? _formBuilderState;
bool _touched = false;
bool _dirty = false;
/// The focus node that is used to focus this field.
late FocusNode effectiveFocusNode;
/// The focus attachment for the [effectiveFocusNode].
FocusAttachment? focusAttachment;
@override
F get widget => super.widget as F;
/// Returns the parent [FormBuilderState] if it exists.
FormBuilderState? get formState => _formBuilderState;
/// Returns the initial value, which may be declared at the field, or by the
/// parent [FormBuilder.initialValue]. When declared at both levels, the field
/// initialValue prevails.
T? get initialValue =>
widget.initialValue ??
(_formBuilderState?.initialValue ??
const <String, dynamic>{})[widget.name]
as T?;
dynamic get transformedValue =>
widget.valueTransformer == null ? value : widget.valueTransformer!(value);
@override
/// Returns the current error text,
/// which may be a validation error or a custom error text.
String? get errorText => super.errorText ?? _customErrorText;
@override
/// Returns `true` if the field has an error or has a custom error text.
bool get hasError => super.hasError || errorText != null;
@override
/// Returns `true` if the field is valid and has no custom error text.
bool get isValid => super.isValid && _customErrorText == null;
/// Returns `true` if the field is valid.
bool get valueIsValid => super.isValid;
/// Returns `true` if the field has an error.
bool get valueHasError => super.hasError;
/// Returns `true` if the field is enabled and the parent FormBuilder is enabled.
bool get enabled => widget.enabled && (_formBuilderState?.enabled ?? true);
/// Returns `true` if the field is read only.
///
/// See [FormBuilder.skipDisabled] for more information.
bool get readOnly => !(_formBuilderState?.widget.skipDisabled ?? false);
/// Will be true if the field is dirty
///
/// The value of field is changed by user or by logic code.
bool get isDirty => _dirty;
/// Will be true if the field is touched
///
/// The field is focused by user or by logic code
bool get isTouched => _touched;
void registerTransformer(Map<String, Function> map) {
final fun = widget.valueTransformer;
if (fun != null) {
map[widget.name] = fun;
}
}
@override
void initState() {
super.initState();
// Register this field when there is a parent FormBuilder
_formBuilderState = FormBuilder.of(context);
// Set the initial value
_formBuilderState?.registerField(widget.name, this);
effectiveFocusNode = widget.focusNode ?? FocusNode(debugLabel: widget.name);
// Register a touch handler
effectiveFocusNode.addListener(_touchedHandler);
focusAttachment = effectiveFocusNode.attach(context);
// Verify if need auto validate form
}
@override
void didUpdateWidget(covariant FormBuilderField<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.name != oldWidget.name) {
_formBuilderState?.unregisterField(oldWidget.name, this);
_formBuilderState?.registerField(widget.name, this);
}
if (widget.focusNode != oldWidget.focusNode) {
focusAttachment?.detach();
effectiveFocusNode.removeListener(_touchedHandler);
effectiveFocusNode =
widget.focusNode ?? FocusNode(canRequestFocus: enabled);
effectiveFocusNode.addListener(_touchedHandler);
focusAttachment = effectiveFocusNode.attach(context);
}
}
@override
void dispose() {
effectiveFocusNode.removeListener(_touchedHandler);
// Checking if the focusNode is handled by the parent or not
if (widget.focusNode == null) {
effectiveFocusNode.dispose();
}
_formBuilderState?.unregisterField(widget.name, this);
super.dispose();
}
void _informFormForFieldChange() {
if (_formBuilderState != null) {
_dirty = value != initialValue;
if (enabled || readOnly) {
_formBuilderState!.setInternalFieldValue<T>(widget.name, value);
return;
}
_formBuilderState!.removeInternalFieldValue(widget.name);
}
}
void _touchedHandler() {
if (effectiveFocusNode.hasFocus && _touched == false) {
setState(() => _touched = true);
}
}
@override
void setValue(T? value, {bool populateForm = true}) {
super.setValue(value);
if (populateForm) {
_informFormForFieldChange();
}
}
@override
void didChange(T? value) {
super.didChange(value);
if (_customErrorText != null) {
setState(() => _customErrorText = null);
}
_informFormForFieldChange();
widget.onChanged?.call(value);
}
@override
/// Reset field value to initial value
///
/// Also reset custom error text if exists, and set [isDirty] to `false`.
void reset() {
super.reset();
_dirty = false;
didChange(initialValue);
if (_customErrorText != null) {
setState(() => _customErrorText = null);
}
}
/// Validate field
///
/// **BREAKING CHANGE**:
/// In previous versions, calling `validate()` would automatically clear any custom errors set via `invalidate()`.
/// Now, `validate()` does not clear custom errors by default.
/// If you want to clear the custom error when validating, you must explicitly pass `clearCustomError: true`.
///
/// Clear custom error if [clearCustomError] is `true`.
/// By default `false`
///
/// Focus when field is invalid if [focusOnInvalid] is `true`.
/// By default `true`
///
/// Auto scroll when focus invalid if [autoScrollWhenFocusOnInvalid] is `true`.
/// By default `false`.
///
/// Note: If a invalid field is from type **TextField** and will focused,
/// the form will auto scroll to show this invalid field.
/// In this case, the automatic scroll happens because is a behavior inside the framework,
/// not because [autoScrollWhenFocusOnInvalid] is `true`.
@override
bool validate({
bool clearCustomError = false,
bool focusOnInvalid = true,
bool autoScrollWhenFocusOnInvalid = false,
}) {
if (clearCustomError) {
setState(() => _customErrorText = null);
}
final isValid = super.validate() && !hasError;
final fields =
_formBuilderState?.fields ??
<String, FormBuilderFieldState<FormBuilderField<dynamic>, dynamic>>{};
if (!isValid &&
focusOnInvalid &&
(formState?.focusOnInvalid ?? true) &&
enabled &&
!fields.values.any((e) => e.effectiveFocusNode.hasFocus)) {
focus();
if (autoScrollWhenFocusOnInvalid) ensureScrollableVisibility();
}
return isValid;
}
/// Invalidate field with a [errorText]
///
/// Focus field if [shouldFocus] is `true`.
/// By default `true`
///
/// Auto scroll when focus invalid if [shouldAutoScrollWhenFocus] is `true`.
/// By default `false`.
///
/// Note: If a invalid field is from type **TextField** and will focused,
/// the form will auto scroll to show this invalid field.
/// In this case, the automatic scroll happens because is a behavior inside the framework,
/// not because [shouldAutoScrollWhenFocus] is `true`.
void invalidate(
String errorText, {
bool shouldFocus = true,
bool shouldAutoScrollWhenFocus = false,
}) {
setState(() => _customErrorText = errorText);
validate(
clearCustomError: false,
autoScrollWhenFocusOnInvalid: shouldAutoScrollWhenFocus,
focusOnInvalid: shouldFocus,
);
}
/// Focus field
void focus() {
FocusScope.of(context).requestFocus(effectiveFocusNode);
}
/// Scroll to show field
void ensureScrollableVisibility() {
Scrollable.ensureVisible(context);
}
}