Repository navigation
Expand file tree
/
Copy pathtext_form_field.dart
More file actions
467 lines (439 loc) · 17.8 KB
/
Copy pathtext_form_field.dart
File metadata and controls
467 lines (439 loc) · 17.8 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle;
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'adaptive_text_selection_toolbar.dart';
import 'input_decorator.dart';
import 'material_state.dart';
import 'text_field.dart';
export 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType;
/// A [FormField] that contains a [TextField].
///
/// This is a convenience widget that wraps a [TextField] widget in a
/// [FormField].
///
/// A [Form] ancestor is not required. The [Form] allows one to
/// save, reset, or validate multiple fields at once. To use without a [Form],
/// pass a `GlobalKey<FormFieldState>` (see [GlobalKey]) to the constructor and use
/// [GlobalKey.currentState] to save or reset the form field.
///
/// When a [controller] is specified, its [TextEditingController.text]
/// defines the [initialValue]. If this [FormField] is part of a scrolling
/// container that lazily constructs its children, like a [ListView] or a
/// [CustomScrollView], then a [controller] should be specified.
/// The controller's lifetime should be managed by a stateful widget ancestor
/// of the scrolling container.
///
/// If a [controller] is not specified, [initialValue] can be used to give
/// the automatically generated controller an initial value.
///
/// {@macro cupertino_ui.textfield.wantKeepAlive}
///
/// Remember to call [TextEditingController.dispose] of the [TextEditingController]
/// when it is no longer needed. This will ensure any resources used by the object
/// are discarded.
///
/// By default, `decoration` will apply the ambient [InputDecorationThemeData] for
/// the current context to the [InputDecoration], see
/// [InputDecoration.applyDefaults].
///
/// For a documentation about the various parameters, see [TextField].
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// Creates a [TextFormField] with an [InputDecoration] and validator function.
///
/// 
///
/// 
///
/// ```dart
/// TextFormField(
/// decoration: const InputDecoration(
/// icon: Icon(Icons.person),
/// hintText: 'What do people call you?',
/// labelText: 'Name *',
/// ),
/// onSaved: (String? value) {
/// // This optional block of code can be used to run
/// // code when the user saves the form.
/// },
/// validator: (String? value) {
/// return (value != null && value.contains('@')) ? 'Do not use the @ char.' : null;
/// },
/// )
/// ```
///
/// </callout-box>
///
/// <callout-box>
///
/// This example shows how to move the focus to the next field when the user
/// presses the SPACE key.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/text_form_field/text_form_field.1.dart#body}
///
/// </callout-box>
///
/// <callout-box>
///
/// This example shows how to force an error text to the field after making
/// an asynchronous call.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/text_form_field/text_form_field.2.dart#body}
///
/// </callout-box>
///
/// See also:
///
/// * <https://material.io/design/components/text-fields.html>
/// * [TextField], which is the underlying text field without the [Form]
/// integration.
/// * [InputDecorator], which shows the labels and other visual elements that
/// surround the actual text editing widget.
/// * Learn how to use a [TextEditingController] in one of our [cookbook recipes](https://docs.flutter.dev/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller).
class TextFormField extends FormField<String> {
/// Creates a [FormField] that contains a [TextField].
///
/// When a [controller] is specified, [initialValue] must be null (the
/// default). If [controller] is null, then a [TextEditingController]
/// will be constructed automatically and its `text` will be initialized
/// to [initialValue] or the empty string.
///
/// For documentation about the various parameters, see the [TextField] class
/// and [TextField.new], the constructor.
TextFormField({
super.key,
this.groupId = EditableText,
this.controller,
String? initialValue,
FocusNode? focusNode,
super.forceErrorText,
InputDecoration? decoration = const InputDecoration(),
TextInputType? keyboardType,
TextCapitalization textCapitalization = TextCapitalization.none,
TextInputAction? textInputAction,
TextStyle? style,
StrutStyle? strutStyle,
TextDirection? textDirection,
TextAlign textAlign = TextAlign.start,
TextAlignVertical? textAlignVertical,
bool autofocus = false,
bool readOnly = false,
@Deprecated(
'Use `contextMenuBuilder` instead. '
'This feature was deprecated after v3.3.0-0.5.pre.',
)
ToolbarOptions? toolbarOptions,
bool? showCursor,
String obscuringCharacter = '•',
bool obscureText = false,
bool autocorrect = true,
SmartDashesType? smartDashesType,
SmartQuotesType? smartQuotesType,
bool enableSuggestions = true,
MaxLengthEnforcement? maxLengthEnforcement,
int? maxLines = 1,
int? minLines,
bool expands = false,
int? maxLength,
this.onChanged,
GestureTapCallback? onTap,
bool onTapAlwaysCalled = false,
TapRegionCallback? onTapOutside,
TapRegionUpCallback? onTapUpOutside,
VoidCallback? onEditingComplete,
ValueChanged<String>? onFieldSubmitted,
super.onSaved,
super.validator,
super.errorBuilder,
List<TextInputFormatter>? inputFormatters,
bool? enabled,
bool? ignorePointers,
double cursorWidth = 2.0,
double? cursorHeight,
Radius? cursorRadius,
Color? cursorColor,
Color? cursorErrorColor,
Brightness? keyboardAppearance,
EdgeInsets scrollPadding = const EdgeInsets.all(20.0),
bool? enableInteractiveSelection,
bool? selectAllOnFocus,
TextSelectionControls? selectionControls,
InputCounterWidgetBuilder? buildCounter,
ScrollPhysics? scrollPhysics,
Iterable<String>? autofillHints,
AutovalidateMode? autovalidateMode,
ScrollController? scrollController,
super.restorationId,
bool enableIMEPersonalizedLearning = true,
bool? enableInlinePrediction,
MouseCursor? mouseCursor,
EditableTextContextMenuBuilder? contextMenuBuilder = _defaultContextMenuBuilder,
SpellCheckConfiguration? spellCheckConfiguration,
TextMagnifierConfiguration? magnifierConfiguration,
UndoHistoryController? undoController,
AppPrivateCommandCallback? onAppPrivateCommand,
bool? cursorOpacityAnimates,
ui.BoxHeightStyle? selectionHeightStyle,
ui.BoxWidthStyle? selectionWidthStyle,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ContentInsertionConfiguration? contentInsertionConfiguration,
MaterialStatesController? statesController,
Clip clipBehavior = Clip.hardEdge,
@Deprecated(
'Use `stylusHandwritingEnabled` instead. '
'This feature was deprecated after v3.27.0-0.2.pre.',
)
bool scribbleEnabled = true,
bool stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled,
bool canRequestFocus = true,
List<Locale>? hintLocales,
}) : assert(initialValue == null || controller == null),
assert(obscuringCharacter.length == 1),
assert(maxLines == null || maxLines > 0),
assert(minLines == null || minLines > 0),
assert(
(maxLines == null) || (minLines == null) || (maxLines >= minLines),
"minLines can't be greater than maxLines",
),
assert(
!expands || (maxLines == null && minLines == null),
'minLines and maxLines must be null when expands is true.',
),
assert(!obscureText || maxLines == 1, 'Obscured fields cannot be multiline.'),
assert(maxLength == null || maxLength == TextField.noMaxLength || maxLength > 0),
assert(
errorBuilder == null || decoration?.errorText == null,
'Declaring both errorBuilder and decoration.errorText is not supported.',
),
super(
initialValue: controller != null ? controller.text : (initialValue ?? ''),
enabled: enabled ?? decoration?.enabled ?? true,
autovalidateMode: autovalidateMode ?? AutovalidateMode.disabled,
builder: (FormFieldState<String> field) {
final state = field as _TextFormFieldState;
InputDecoration effectiveDecoration = (decoration ?? const InputDecoration())
.applyDefaults(InputDecorationTheme.of(field.context));
final String? errorText = field.errorText;
if (errorText != null) {
effectiveDecoration = errorBuilder != null
? effectiveDecoration.copyWith(error: errorBuilder(state.context, errorText))
: effectiveDecoration.copyWith(errorText: errorText);
}
void onChangedHandler(String value) {
field.didChange(value);
onChanged?.call(value);
}
return UnmanagedRestorationScope(
bucket: field.bucket,
child: TextField(
groupId: groupId,
restorationId: restorationId,
controller: state._effectiveController,
focusNode: focusNode,
decoration: effectiveDecoration,
keyboardType: keyboardType,
textInputAction: textInputAction,
style: style,
strutStyle: strutStyle,
textAlign: textAlign,
textAlignVertical: textAlignVertical,
textDirection: textDirection,
textCapitalization: textCapitalization,
autofocus: autofocus,
statesController: statesController,
toolbarOptions: toolbarOptions,
readOnly: readOnly,
showCursor: showCursor,
obscuringCharacter: obscuringCharacter,
obscureText: obscureText,
autocorrect: autocorrect,
smartDashesType:
smartDashesType ??
(obscureText ? SmartDashesType.disabled : SmartDashesType.enabled),
smartQuotesType:
smartQuotesType ??
(obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled),
enableSuggestions: enableSuggestions,
maxLengthEnforcement: maxLengthEnforcement,
maxLines: maxLines,
minLines: minLines,
expands: expands,
maxLength: maxLength,
onChanged: onChangedHandler,
onTap: onTap,
onTapAlwaysCalled: onTapAlwaysCalled,
onTapOutside: onTapOutside,
onTapUpOutside: onTapUpOutside,
onEditingComplete: onEditingComplete,
onSubmitted: onFieldSubmitted,
inputFormatters: inputFormatters,
enabled: enabled ?? decoration?.enabled ?? true,
ignorePointers: ignorePointers,
cursorWidth: cursorWidth,
cursorHeight: cursorHeight,
cursorRadius: cursorRadius,
cursorColor: cursorColor,
cursorErrorColor: cursorErrorColor,
scrollPadding: scrollPadding,
scrollPhysics: scrollPhysics,
keyboardAppearance: keyboardAppearance,
enableInteractiveSelection:
enableInteractiveSelection ?? (!obscureText || !readOnly),
selectAllOnFocus: selectAllOnFocus,
selectionControls: selectionControls,
buildCounter: buildCounter,
autofillHints: autofillHints,
scrollController: scrollController,
enableIMEPersonalizedLearning: enableIMEPersonalizedLearning,
enableInlinePrediction: enableInlinePrediction,
mouseCursor: mouseCursor,
contextMenuBuilder: contextMenuBuilder,
spellCheckConfiguration: spellCheckConfiguration,
magnifierConfiguration: magnifierConfiguration,
undoController: undoController,
onAppPrivateCommand: onAppPrivateCommand,
cursorOpacityAnimates: cursorOpacityAnimates,
selectionHeightStyle:
selectionHeightStyle ?? EditableText.defaultSelectionHeightStyle,
selectionWidthStyle: selectionWidthStyle ?? EditableText.defaultSelectionWidthStyle,
dragStartBehavior: dragStartBehavior,
contentInsertionConfiguration: contentInsertionConfiguration,
clipBehavior: clipBehavior,
scribbleEnabled: scribbleEnabled,
stylusHandwritingEnabled: stylusHandwritingEnabled,
canRequestFocus: canRequestFocus,
hintLocales: hintLocales,
),
);
},
);
/// Controls the text being edited.
///
/// If null, this widget will create its own [TextEditingController] and
/// initialize its [TextEditingController.text] with [initialValue].
final TextEditingController? controller;
/// {@macro flutter.widgets.editableText.groupId}
final Object groupId;
/// {@macro cupertino_ui.TextFormField.onChanged}
final ValueChanged<String>? onChanged;
static Widget _defaultContextMenuBuilder(
BuildContext context,
EditableTextState editableTextState,
) {
if (SystemContextMenu.isSupportedByField(editableTextState)) {
return SystemContextMenu.editableText(editableTextState: editableTextState);
}
return AdaptiveTextSelectionToolbar.editableText(editableTextState: editableTextState);
}
@override
FormFieldState<String> createState() => _TextFormFieldState();
}
class _TextFormFieldState extends FormFieldState<String> {
RestorableTextEditingController? _controller;
late final String? _initialValue;
TextEditingController get _effectiveController => _textFormField.controller ?? _controller!.value;
TextFormField get _textFormField => super.widget as TextFormField;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
super.restoreState(oldBucket, initialRestore);
if (_controller != null) {
_registerController();
}
// Make sure to update the internal [FormFieldState] value to sync up with
// text editing controller value.
setValue(_effectiveController.text);
}
void _registerController() {
assert(_controller != null);
registerForRestoration(_controller!, 'controller');
}
void _createLocalController([TextEditingValue? value]) {
assert(_controller == null);
_controller = value == null
? RestorableTextEditingController()
: RestorableTextEditingController.fromValue(value);
if (!restorePending) {
_registerController();
}
}
@override
void initState() {
super.initState();
if (_textFormField.controller == null) {
_createLocalController(
widget.initialValue != null ? TextEditingValue(text: widget.initialValue!) : null,
);
} else {
_textFormField.controller!.addListener(_handleControllerChanged);
}
_initialValue = _textFormField.initialValue ?? _textFormField.controller?.text;
}
@override
void didUpdateWidget(TextFormField oldWidget) {
super.didUpdateWidget(oldWidget);
if (_textFormField.controller != oldWidget.controller) {
oldWidget.controller?.removeListener(_handleControllerChanged);
_textFormField.controller?.addListener(_handleControllerChanged);
if (oldWidget.controller != null && _textFormField.controller == null) {
_createLocalController(oldWidget.controller!.value);
}
if (_textFormField.controller != null) {
setValue(_textFormField.controller!.text);
if (oldWidget.controller == null) {
unregisterFromRestoration(_controller!);
_controller!.dispose();
_controller = null;
}
}
}
}
@override
void dispose() {
_textFormField.controller?.removeListener(_handleControllerChanged);
_controller?.dispose();
super.dispose();
}
@override
void didChange(String? value) {
super.didChange(value);
if (_effectiveController.text != value) {
_effectiveController.value = TextEditingValue(text: value ?? '');
}
}
@override
void reset() {
// Set the controller value before calling super.reset() to let
// _handleControllerChanged suppress the change.
_effectiveController.value = TextEditingValue(text: _initialValue ?? '');
super.reset();
_textFormField.onChanged?.call(_effectiveController.text);
}
void _handleControllerChanged() {
// Suppress changes that originated from within this class.
//
// In the case where a controller has been passed in to this widget, we
// register this change listener. In these cases, we'll also receive change
// notifications for changes originating from within this class -- for
// example, the reset() method. In such cases, the FormField value will
// already have been set.
if (_effectiveController.text != value) {
didChange(_effectiveController.text);
}
}
}