-
-
Notifications
You must be signed in to change notification settings - Fork 562
Expand file tree
/
Copy pathform_builder.dart
More file actions
301 lines (260 loc) · 9.37 KB
/
form_builder.dart
File metadata and controls
301 lines (260 loc) · 9.37 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
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.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;
/// Enables the form to veto attempts by the user to dismiss the [ModalRoute]
/// that contains the form.
///
/// If the callback returns a Future that resolves to false, the form's route
/// will not be popped.
///
/// See also:
///
/// * [WillPopScope], another widget that provides a way to intercept the
/// back button.
final WillPopCallback? onWillPop;
/// 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.
///
/// 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 the form should auto focus on the first field that fails validation.
final bool autoFocusOnValidationFailure;
/// 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.onWillPop,
this.initialValue = const <String, dynamic>{},
this.skipDisabled = false,
this.enabled = true,
this.autoFocusOnValidationFailure = false,
this.clearValueOnUnregister = false,
});
static FormBuilderState? of(BuildContext context) =>
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 _formKey = GlobalKey<FormState>();
bool get enabled => widget.enabled;
final FormBuilderFields _fields = {};
//because dart type system will not accept ValueTransformer<dynamic>
final _transformers = <String, Function>{};
final _instantValue = <String, dynamic>{};
final _savedValue = <String, dynamic>{};
final _onChangedStreamController = StreamController<FormBuilderFields>();
Map<String, dynamic> get instantValue =>
Map<String, dynamic>.unmodifiable(_instantValue.map((key, value) =>
MapEntry(key, _transformers[key]?.call(value) ?? value)));
/// Returns the saved value only
Map<String, dynamic> get value =>
Map<String, dynamic>.unmodifiable(_savedValue.map((key, value) =>
MapEntry(key, _transformers[key]?.call(value) ?? value)));
/// Returns values after saving
Map<String, dynamic> get initialValue => widget.initialValue;
FormBuilderFields get fields => _fields;
/// A stream that informs the subscribers when the form changes.
Stream<FormBuilderFields> get onChanged => _onChangedStreamController.stream;
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];
}
void setInternalFieldValue<T>(String name, T? value,
{required bool isSetState}) {
_instantValue[name] = value;
if (isSetState) {
setState(() {});
}
widget.onChanged?.call();
_onChangedStreamController.add(fields);
}
bool get isValid =>
fields.values.where((element) => !element.isValid).isEmpty;
void removeInternalFieldValue(
String name, {
required bool isSetState,
}) {
_instantValue.remove(name);
if (isSetState) {
setState(() {});
}
_onChangedStreamController.add(fields);
}
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 (oldField != null) {
// ignore: invalid_use_of_protected_member
field.setValue(oldField.value, populateForm: false);
} else {
// ignore: invalid_use_of_protected_member
field.setValue(
_instantValue[name] ??= field.initialValue,
populateForm: false,
);
}
_onChangedStreamController.add(fields);
}
void unregisterField(String name, FormBuilderFieldState field) {
assert(_fields.containsKey(name));
// 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;
}());
}
_onChangedStreamController.add(fields);
}
void save() {
_formKey.currentState!.save();
//copy values from instant to saved
_savedValue.clear();
_savedValue.addAll(_instantValue);
}
void invalidateField({required String name, String? errorText}) =>
fields[name]?.invalidate(errorText ?? '');
void invalidateFirstField({required String errorText}) =>
fields.values.first.invalidate(errorText);
bool validate() {
final hasError = !_formKey.currentState!.validate();
if (hasError && widget.autoFocusOnValidationFailure) {
final wrongFields =
fields.values.where((element) => element.hasError).toList();
wrongFields.first.requestFocus();
}
return !hasError;
}
bool saveAndValidate() {
save();
return validate();
}
void reset() {
log('reset called');
_formKey.currentState!.reset();
for (var item in _fields.entries) {
try {
item.value.didChange(getRawValue(item.key));
} catch (e, st) {
log(
'Error when resetting field: ${item.key}',
error: e,
stackTrace: st,
level: 2000,
);
}
}
// _formKey.currentState!.setState(() {});
}
void patchValue(Map<String, dynamic> val) {
val.forEach((key, dynamic value) {
_fields[key]?.didChange(value);
});
}
@override
void dispose() {
_onChangedStreamController.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidateMode: widget.autovalidateMode,
onWillPop: widget.onWillPop,
// `onChanged` is called during setInternalFieldValue else will be called early
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: widget.child,
),
);
}
}