-
-
Notifications
You must be signed in to change notification settings - Fork 562
Expand file tree
/
Copy pathform_builder.dart
More file actions
421 lines (374 loc) · 13.6 KB
/
form_builder.dart
File metadata and controls
421 lines (374 loc) · 13.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import 'package:flutter/widgets.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_form_builder/src/extensions/autovalidatemode_extension.dart';
/// A container for form fields.
class FormBuilder extends StatefulWidget {
/// Called when one of the form fields changes.
///
/// In addition to this callback being invoked, all the form fields themselves
/// will rebuild.
final VoidCallback? onChanged;
/// {@macro flutter.widgets.navigator.onPopInvokedWithResult}
///
/// {@tool dartpad}
/// This sample demonstrates how to use this parameter to show a confirmation
/// dialog when a navigation pop would cause form data to be lost.
///
/// ** See code in examples/api/lib/widgets/form/form.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [canPop], which also comes from [PopScope] and is often used in
/// conjunction with this parameter.
/// * [PopScope.onPopInvokedWithResult], which is what [Form] delegates to internally.
final PopInvokedWithResultCallback<Object?>? onPopInvokedWithResult;
/// {@macro flutter.widgets.PopScope.canPop}
///
/// {@tool dartpad}
/// This sample demonstrates how to use this parameter to show a confirmation
/// dialog when a navigation pop would cause form data to be lost.
///
/// ** See code in examples/api/lib/widgets/form/form.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [onPopInvoked], which also comes from [PopScope] and is often used in
/// conjunction with this parameter.
/// * [PopScope.canPop], which is what [Form] delegates to internally.
final bool? canPop;
/// The widget below this widget in the tree.
///
/// This is the root of the widget hierarchy that contains this form.
///
/// {@macro flutter.widgets.child}
final Widget child;
/// Used to enable/disable form fields auto validation and update their error
/// text.
///
/// {@macro flutter.widgets.form.autovalidateMode}
final AutovalidateMode? autovalidateMode;
/// An optional Map of field initialValues. Keys correspond to the field's
/// name and value to the initialValue of the field.
///
/// The initialValues set here will be ignored if the field has a local
/// initialValue set.
final Map<String, dynamic> initialValue;
/// Whether the form should ignore submitting values from fields where
/// `enabled` is `false`.
///
/// This behavior is common in HTML forms where _readonly_ values are not
/// submitted when the form is submitted.
///
/// `true` = Disabled / `false` = Read only
///
/// When `true`, the final form value will not contain disabled fields.
/// Default is `false`.
final bool skipDisabled;
/// Whether the form is able to receive user input.
///
/// Defaults to true.
///
/// When `false` all the form fields will be disabled - won't accept input -
/// and their enabled state will be ignored.
final bool enabled;
/// Whether to clear the internal value of a field when it is unregistered.
///
/// Defaults to `false`.
///
/// When set to `true`, the form builder will not keep the internal values
/// from disposed [FormBuilderField]s. This is useful for dynamic forms where
/// fields are registered and unregistered due to state change.
///
/// This setting will have no effect when registering a field with the same
/// name as the unregistered one.
final bool clearValueOnUnregister;
/// Creates a container for form fields.
///
/// The [child] argument must not be null.
const FormBuilder({
super.key,
required this.child,
this.onChanged,
this.autovalidateMode,
this.onPopInvokedWithResult,
this.initialValue = const <String, dynamic>{},
this.skipDisabled = false,
this.enabled = true,
this.clearValueOnUnregister = false,
this.canPop,
});
static FormBuilderState of(BuildContext context, [bool listen = false]) {
final FormBuilderState? formState = maybeOf(context, listen);
assert(() {
if (formState == null) {
throw FlutterError(
'FormBuilder.of() was called with a context that does not contain a FormBuilder widget.\n'
'No FormBuilder widget ancestor could be found starting from the context that '
'was passed to FormBuilder.of(). This can happen because you are using a widget '
'that looks for a FormBuilder ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return formState!;
}
static FormBuilderState? maybeOf(
BuildContext context, [
bool listen = false,
]) {
if (listen) {
return context
.dependOnInheritedWidgetOfExactType<_FormBuilderScope>()
?._formState;
}
return context.findAncestorStateOfType<FormBuilderState>();
}
@override
FormBuilderState createState() => FormBuilderState();
}
/// A type alias for a map of form fields.
typedef FormBuilderFields =
Map<String, FormBuilderFieldState<FormBuilderField<dynamic>, dynamic>>;
class FormBuilderState extends State<FormBuilder> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final FormBuilderFields _fields = {};
final Map<String, dynamic> _instantValue = {};
final Map<String, dynamic> _savedValue = {};
// Because dart type system will not accept ValueTransformer<dynamic>
final Map<String, Function> _transformers = {};
bool _focusOnInvalid = true;
/// Will be true if will focus on invalid field when validate
///
/// Only used to internal logic
bool get focusOnInvalid => _focusOnInvalid;
/// Get if form is enabled
bool get enabled => widget.enabled;
/// Verify if all fields on form are valid.
bool get isValid => fields.values.every((field) => field.isValid);
/// Will be true if some field on form are dirty.
///
/// Dirty: The value of field is changed by user or by logic code.
bool get isDirty => fields.values.any((field) => field.isDirty);
/// Will be true if some field on form are touched.
///
/// Touched: The field is focused by user or by logic code.
bool get isTouched => fields.values.any((field) => field.isTouched);
/// Get a map of errors
Map<String, String> get errors => {
for (var element in fields.entries.where(
(element) => element.value.hasError,
))
element.key.toString(): element.value.errorText ?? '',
};
/// Get initialValue.
Map<String, dynamic> get initialValue => widget.initialValue;
/// Get all fields of form.
FormBuilderFields get fields => _fields;
/// Get all fields values of form.
Map<String, dynamic> get instantValue => Map<String, dynamic>.unmodifiable(
_instantValue.map(
(key, value) => MapEntry(
key,
_transformers[key] == null ? value : _transformers[key]!(value),
),
),
);
/// Returns the saved value only
Map<String, dynamic> get value => Map<String, dynamic>.unmodifiable(
_savedValue.map(
(key, value) => MapEntry(
key,
_transformers[key] == null ? value : _transformers[key]!(value),
),
),
);
dynamic transformValue<T>(String name, T? v) {
final t = _transformers[name];
return t != null ? t.call(v) : v;
}
dynamic getTransformedValue<T>(String name, {bool fromSaved = false}) {
return transformValue<T>(name, getRawValue(name));
}
T? getRawValue<T>(String name, {bool fromSaved = false}) {
return (fromSaved ? _savedValue[name] : _instantValue[name]) ??
initialValue[name];
}
/// Get a field value by name
void setInternalFieldValue<T>(String name, T? value) {
_instantValue[name] = value;
widget.onChanged?.call();
}
/// Remove a field value by name
void removeInternalFieldValue(String name) {
_instantValue.remove(name);
}
/// Register a field on form
void registerField(String name, FormBuilderFieldState field) {
// Each field must have a unique name. Ideally we could simply:
// assert(!_fields.containsKey(name));
// However, Flutter will delay dispose of deactivated fields, so if a
// field is being replaced, the new instance is registered before the old
// one is unregistered. To accommodate that use case, but also provide
// assistance to accidental duplicate names, we check and emit a warning.
final oldField = _fields[name];
assert(() {
if (oldField != null) {
debugPrint(
'Warning! Replacing duplicate Field for $name'
' -- this is OK to ignore as long as the field was intentionally replaced',
);
}
return true;
}());
_fields[name] = field;
field.registerTransformer(_transformers);
if (widget.clearValueOnUnregister || (_instantValue[name] == null)) {
_instantValue[name] = field.initialValue ?? initialValue[name];
}
field.setValue(_instantValue[name], populateForm: false);
}
/// Unregister a field on form
void unregisterField(String name, FormBuilderFieldState field) {
assert(
_fields.containsKey(name),
'Failed to unregister a field. Make sure that all field names in a form are unique.',
);
// Only remove the field when it is the one registered. It's possible that
// the field is replaced (registerField is called twice for a given name)
// before unregisterField is called for the name, so just emit a warning
// since it may be intentional.
if (field == _fields[name]) {
_fields.remove(name);
_transformers.remove(name);
if (widget.clearValueOnUnregister) {
_instantValue.remove(name);
_savedValue.remove(name);
}
} else {
assert(() {
// This is OK to ignore when you are intentionally replacing a field
// with another field using the same name.
debugPrint(
'Warning! Ignoring Field unregistration for $name'
' -- this is OK to ignore as long as the field was intentionally replaced',
);
return true;
}());
}
}
/// Save form values
void save() {
_formKey.currentState!.save();
// Copy values from instant to saved
_savedValue.clear();
_savedValue.addAll(_instantValue);
}
/// Validate all fields of form
///
/// Focus to first invalid field when has field invalid, if [focusOnInvalid] is `true`.
/// By default `true`
///
/// Auto scroll to first invalid field focused 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`.
bool validate({
bool focusOnInvalid = true,
bool autoScrollWhenFocusOnInvalid = false,
}) {
_focusOnInvalid = focusOnInvalid;
final hasError = !_formKey.currentState!.validate();
if (hasError) {
final wrongFields =
fields.values.where((element) => element.hasError).toList();
if (wrongFields.isNotEmpty) {
if (focusOnInvalid) {
wrongFields.first.focus();
}
if (autoScrollWhenFocusOnInvalid) {
wrongFields.first.ensureScrollableVisibility();
}
}
}
return !hasError;
}
/// Save form values and validate all fields of form
///
/// Focus to first invalid field when has field invalid, if [focusOnInvalid] is `true`.
/// By default `true`
///
/// Auto scroll to first invalid field focused 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`.
bool saveAndValidate({
bool focusOnInvalid = true,
bool autoScrollWhenFocusOnInvalid = false,
}) {
save();
return validate(
focusOnInvalid: focusOnInvalid,
autoScrollWhenFocusOnInvalid: autoScrollWhenFocusOnInvalid,
);
}
/// Reset form to `initialValue` set on FormBuilder or on each field.
void reset() {
_formKey.currentState?.reset();
}
/// Update fields values of form.
/// Useful when need update all values at once, after init.
///
/// To load all values at once on init, use `initialValue` property
void patchValue(Map<String, dynamic> val) {
val.forEach((key, dynamic value) {
_fields[key]?.didChange(value);
});
}
@override
void initState() {
// Verify if need auto validate form
if (enabled && (widget.autovalidateMode?.isAlways ?? false)) {
WidgetsBinding.instance.addPostFrameCallback((_) {
// No focus on invalid, like default behavior on Flutter base Form
validate(focusOnInvalid: false);
});
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidateMode: widget.autovalidateMode,
onPopInvokedWithResult: widget.onPopInvokedWithResult,
canPop: widget.canPop,
// `onChanged` is called during setInternalFieldValue else will be called early
child: _FormBuilderScope(
formState: this,
child: FocusTraversalGroup(child: widget.child),
),
);
}
}
class _FormBuilderScope extends InheritedWidget {
const _FormBuilderScope({
required super.child,
required FormBuilderState formState,
}) : _formState = formState;
final FormBuilderState _formState;
/// The [Form] associated with this widget.
FormBuilder get form => _formState.widget;
@override
bool updateShouldNotify(_FormBuilderScope oldWidget) =>
oldWidget._formState != _formState;
}