form.dart 16.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'framework.dart';
6
import 'navigator.dart';
7
import 'will_pop_scope.dart';
8

9
/// An optional container for grouping together multiple form field widgets
10
/// (e.g. [TextField] widgets).
11 12 13 14 15 16 17
///
/// Each individual form field should be wrapped in a [FormField] widget, with
/// the [Form] widget as a common ancestor of all of those. Call methods on
/// [FormState] to save, reset, or validate each [FormField] that is a
/// descendant of this [Form]. To obtain the [FormState], you may use [Form.of]
/// with a context whose ancestor is the [Form], or pass a [GlobalKey] to the
/// [Form] constructor and call [GlobalKey.currentState].
18
///
19
/// {@tool dartpad --template=stateful_widget_scaffold}
20
/// This example shows a [Form] with one [TextFormField] to enter an email
21
/// address and an [ElevatedButton] to submit the form. A [GlobalKey] is used here
22 23 24
/// to identify the [Form] and validate input.
///
/// ![](https://flutter.github.io/assets-for-api-docs/assets/widgets/form.png)
25 26
///
/// ```dart
27
/// final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
28 29 30 31 32 33 34 35 36
///
/// @override
/// Widget build(BuildContext context) {
///   return Form(
///     key: _formKey,
///     child: Column(
///       crossAxisAlignment: CrossAxisAlignment.start,
///       children: <Widget>[
///         TextFormField(
37 38 39
///           decoration: const InputDecoration(
///             hintText: 'Enter your email',
///           ),
40 41
///           validator: (String? value) {
///             if (value == null || value.isEmpty) {
42 43
///               return 'Please enter some text';
///             }
44
///             return null;
45 46 47 48
///           },
///         ),
///         Padding(
///           padding: const EdgeInsets.symmetric(vertical: 16.0),
49
///           child: ElevatedButton(
50 51 52
///             onPressed: () {
///               // Validate will return true if the form is valid, or false if
///               // the form is invalid.
53
///               if (_formKey.currentState!.validate()) {
54 55 56
///                 // Process data.
///               }
///             },
57
///             child: const Text('Submit'),
58 59 60 61 62 63 64 65 66 67 68 69 70 71
///           ),
///         ),
///       ],
///     ),
///   );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
///  * [GlobalKey], a key that is unique across the entire app.
///  * [FormField], a single form field widget that maintains the current state.
///  * [TextFormField], a convenience widget that wraps a [TextField] widget in a [FormField].
72
class Form extends StatefulWidget {
73 74 75
  /// Creates a container for form fields.
  ///
  /// The [child] argument must not be null.
76
  const Form({
77 78
    Key? key,
    required this.child,
79
    @Deprecated(
80
      'Use autovalidateMode parameter which provides more specific '
81
      'behavior related to auto validation. '
82
      'This feature was deprecated after v1.19.0.',
83
    )
84
    this.autovalidate = false,
85
    this.onWillPop,
86
    this.onChanged,
87
    AutovalidateMode? autovalidateMode,
88
  }) : assert(child != null),
89 90 91 92
       assert(autovalidate != null),
       assert(
         autovalidate == false ||
         autovalidate == true && autovalidateMode == null,
93
         'autovalidate and autovalidateMode should not be used together.',
94
       ),
95 96
       autovalidateMode = autovalidateMode ??
         (autovalidate ? AutovalidateMode.always : AutovalidateMode.disabled),
97
       super(key: key);
98

Matt Perry's avatar
Matt Perry committed
99 100 101 102 103 104 105 106
  /// Returns the closest [FormState] which encloses the given context.
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// FormState form = Form.of(context);
  /// form.save();
  /// ```
107 108
  static FormState? of(BuildContext context) {
    final _FormScope? scope = context.dependOnInheritedWidgetOfExactType<_FormScope>();
Matt Perry's avatar
Matt Perry committed
109 110
    return scope?._formState;
  }
111

112 113 114 115
  /// The widget below this widget in the tree.
  ///
  /// This is the root of the widget hierarchy that contains this form.
  ///
116
  /// {@macro flutter.widgets.ProxyWidget.child}
117 118
  final Widget child;

119 120 121 122 123
  /// 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.
124 125 126 127 128
  ///
  /// See also:
  ///
  ///  * [WillPopScope], another widget that provides a way to intercept the
  ///    back button.
129
  final WillPopCallback? onWillPop;
130

131 132 133 134
  /// Called when one of the form fields changes.
  ///
  /// In addition to this callback being invoked, all the form fields themselves
  /// will rebuild.
135
  final VoidCallback? onChanged;
136

137 138 139
  /// Used to enable/disable form fields auto validation and update their error
  /// text.
  ///
140
  /// {@macro flutter.widgets.FormField.autovalidateMode}
141 142
  final AutovalidateMode autovalidateMode;

143 144 145
  /// Used to enable/disable form fields auto validation and update their error
  /// text.
  @Deprecated(
146
    'Use autovalidateMode parameter which provides more specific '
147
    'behavior related to auto validation. '
148
    'This feature was deprecated after v1.19.0.',
149 150 151
  )
  final bool autovalidate;

152
  @override
153
  FormState createState() => FormState();
154 155
}

156
/// State associated with a [Form] widget.
157
///
158
/// A [FormState] object can be used to [save], [reset], and [validate] every
159 160 161
/// [FormField] that is a descendant of the associated [Form].
///
/// Typically obtained via [Form.of].
Matt Perry's avatar
Matt Perry committed
162 163
class FormState extends State<Form> {
  int _generation = 0;
164
  bool _hasInteractedByUser = false;
165
  final Set<FormFieldState<dynamic>> _fields = <FormFieldState<dynamic>>{};
166

167 168
  // Called when a form field has changed. This will cause all form fields
  // to rebuild, useful if form fields have interdependencies.
Matt Perry's avatar
Matt Perry committed
169
  void _fieldDidChange() {
170
    widget.onChanged?.call();
171 172 173

    _hasInteractedByUser = _fields
        .any((FormFieldState<dynamic> field) => field._hasInteractedByUser);
174 175 176 177
    _forceRebuild();
  }

  void _forceRebuild() {
178
    setState(() {
Matt Perry's avatar
Matt Perry committed
179
      ++_generation;
180 181 182
    });
  }

Matt Perry's avatar
Matt Perry committed
183 184 185 186 187 188 189 190
  void _register(FormFieldState<dynamic> field) {
    _fields.add(field);
  }

  void _unregister(FormFieldState<dynamic> field) {
    _fields.remove(field);
  }

191 192
  @override
  Widget build(BuildContext context) {
193 194 195 196 197 198 199 200 201 202 203 204 205
    switch (widget.autovalidateMode) {
      case AutovalidateMode.always:
        _validate();
        break;
      case AutovalidateMode.onUserInteraction:
        if (_hasInteractedByUser) {
          _validate();
        }
        break;
      case AutovalidateMode.disabled:
        break;
    }

206
    return WillPopScope(
207
      onWillPop: widget.onWillPop,
208
      child: _FormScope(
209 210
        formState: this,
        generation: _generation,
211
        child: widget.child,
212
      ),
213 214 215
    );
  }

216
  /// Saves every [FormField] that is a descendant of this [Form].
Matt Perry's avatar
Matt Perry committed
217
  void save() {
218
    for (final FormFieldState<dynamic> field in _fields)
Matt Perry's avatar
Matt Perry committed
219 220
      field.save();
  }
221

222
  /// Resets every [FormField] that is a descendant of this [Form] back to its
223
  /// [FormField.initialValue].
224 225 226
  ///
  /// The [Form.onChanged] callback will be called.
  ///
227 228
  /// If the form's [Form.autovalidateMode] property is [AutovalidateMode.always],
  /// the fields will all be revalidated after being reset.
Matt Perry's avatar
Matt Perry committed
229
  void reset() {
230
    for (final FormFieldState<dynamic> field in _fields)
Matt Perry's avatar
Matt Perry committed
231
      field.reset();
232
    _hasInteractedByUser = false;
Matt Perry's avatar
Matt Perry committed
233 234
    _fieldDidChange();
  }
235

236
  /// Validates every [FormField] that is a descendant of this [Form], and
237
  /// returns true if there are no errors.
238 239
  ///
  /// The form will rebuild to report the results.
240
  bool validate() {
241
    _hasInteractedByUser = true;
242
    _forceRebuild();
243 244 245 246 247
    return _validate();
  }

  bool _validate() {
    bool hasError = false;
248
    for (final FormFieldState<dynamic> field in _fields)
249 250
      hasError = !field.validate() || hasError;
    return !hasError;
Matt Perry's avatar
Matt Perry committed
251
  }
252 253
}

Matt Perry's avatar
Matt Perry committed
254
class _FormScope extends InheritedWidget {
255
  const _FormScope({
256 257 258 259
    Key? key,
    required Widget child,
    required FormState formState,
    required int generation,
260
  }) : _formState = formState,
261 262 263
       _generation = generation,
       super(key: key, child: child);

Matt Perry's avatar
Matt Perry committed
264
  final FormState _formState;
265 266 267 268 269

  /// Incremented every time a form field has changed. This lets us know when
  /// to rebuild the form.
  final int _generation;

270
  /// The [Form] associated with this widget.
271
  Form get form => _formState.widget;
272

Matt Perry's avatar
Matt Perry committed
273 274 275 276 277
  @override
  bool updateShouldNotify(_FormScope old) => _generation != old._generation;
}

/// Signature for validating a form field.
278
///
279 280 281
/// Returns an error string to display if the input is invalid, or null
/// otherwise.
///
282
/// Used by [FormField.validator].
283
typedef FormFieldValidator<T> = String? Function(T? value);
Matt Perry's avatar
Matt Perry committed
284 285

/// Signature for being notified when a form field changes value.
286 287
///
/// Used by [FormField.onSaved].
288
typedef FormFieldSetter<T> = void Function(T? newValue);
Matt Perry's avatar
Matt Perry committed
289 290

/// Signature for building the widget representing the form field.
291 292
///
/// Used by [FormField.builder].
293
typedef FormFieldBuilder<T> = Widget Function(FormFieldState<T> field);
Matt Perry's avatar
Matt Perry committed
294

295 296 297 298
/// 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.
Matt Perry's avatar
Matt Perry committed
299 300 301 302 303 304 305 306
///
/// When used inside a [Form], you can use methods on [FormState] to query or
/// manipulate the form data as a whole. For example, calling [FormState.save]
/// will invoke each [FormField]'s [onSaved] callback in turn.
///
/// Use a [GlobalKey] with [FormField] if you want to retrieve its current
/// state, for example if you want one form field to depend on another.
///
307 308 309 310 311
/// A [Form] ancestor is not required. The [Form] simply makes it easier to
/// save, reset, or validate multiple fields at once. To use without a [Form],
/// pass a [GlobalKey] to the constructor and use [GlobalKey.currentState] to
/// save or reset the form field.
///
312 313 314 315
/// See also:
///
///  * [Form], which is the widget that aggregates the form fields.
///  * [TextField], which is a commonly used form field for entering text.
Matt Perry's avatar
Matt Perry committed
316
class FormField<T> extends StatefulWidget {
317 318 319
  /// Creates a single form field.
  ///
  /// The [builder] argument must not be null.
320
  const FormField({
321 322
    Key? key,
    required this.builder,
Matt Perry's avatar
Matt Perry committed
323 324 325
    this.onSaved,
    this.validator,
    this.initialValue,
326
    @Deprecated(
327
      'Use autovalidateMode parameter which provides more specific '
328
      'behavior related to auto validation. '
329
      'This feature was deprecated after v1.19.0.',
330
    )
331
    this.autovalidate = false,
332
    this.enabled = true,
333
    AutovalidateMode? autovalidateMode,
334
  }) : assert(builder != null),
335 336 337
       assert(
         autovalidate == false ||
         autovalidate == true && autovalidateMode == null,
338
         'autovalidate and autovalidateMode should not be used together.',
339
       ),
340 341
        autovalidateMode = autovalidateMode ??
          (autovalidate ? AutovalidateMode.always : AutovalidateMode.disabled),
342
       super(key: key);
343

Matt Perry's avatar
Matt Perry committed
344
  /// An optional method to call with the final value when the form is saved via
345
  /// [FormState.save].
346
  final FormFieldSetter<T>? onSaved;
Matt Perry's avatar
Matt Perry committed
347 348 349

  /// An optional method that validates an input. Returns an error string to
  /// display if the input is invalid, or null otherwise.
350 351 352 353
  ///
  /// The returned value is exposed by the [FormFieldState.errorText] property.
  /// The [TextFormField] uses this to override the [InputDecoration.errorText]
  /// value.
354 355 356 357 358
  ///
  /// Alternating between error and normal state can cause the height of the
  /// [TextFormField] to change if no other subtext decoration is set on the
  /// field. To create a field whose height is fixed regardless of whether or
  /// not an error is displayed, either wrap the  [TextFormField] in a fixed
359
  /// height parent like [SizedBox], or set the [InputDecoration.helperText]
360
  /// parameter to a space.
361
  final FormFieldValidator<T>? validator;
Matt Perry's avatar
Matt Perry committed
362 363 364 365 366 367 368

  /// Function that returns the widget representing this form field. It is
  /// passed the form field state as input, containing the current value and
  /// validation state of this field.
  final FormFieldBuilder<T> builder;

  /// An optional value to initialize the form field to, or null otherwise.
369
  final T? initialValue;
370

371 372
  /// Whether the form is able to receive user input.
  ///
373 374 375
  /// Defaults to true. If [autovalidateMode] is not [AutovalidateMode.disabled],
  /// the field will be auto validated. Likewise, if this field is false, the widget
  /// will not be validated regardless of [autovalidateMode].
376 377
  final bool enabled;

378 379 380
  /// Used to enable/disable this form field auto validation and update its
  /// error text.
  ///
381
  /// {@template flutter.widgets.FormField.autovalidateMode}
382 383 384 385 386
  /// If [AutovalidateMode.onUserInteraction] this form field will only
  /// auto-validate after its content changes, if [AutovalidateMode.always] it
  /// will auto validate even without user interaction and
  /// if [AutovalidateMode.disabled] the auto validation will be disabled.
  ///
387 388
  /// Defaults to [AutovalidateMode.disabled] if `autovalidate` is false which
  /// means no auto validation will occur. If `autovalidate` is true then this
389 390 391 392
  /// is set to [AutovalidateMode.always] for backward compatibility.
  /// {@endtemplate}
  final AutovalidateMode autovalidateMode;

393 394 395
  /// Used to enable/disable auto validation and update their error
  /// text.
  @Deprecated(
396
    'Use autovalidateMode parameter which provides more specific '
397
    'behavior related to auto validation. '
398
    'This feature was deprecated after v1.19.0.',
399 400 401
  )
  final bool autovalidate;

402
  @override
403
  FormFieldState<T> createState() => FormFieldState<T>();
Matt Perry's avatar
Matt Perry committed
404 405
}

406 407
/// The current state of a [FormField]. Passed to the [FormFieldBuilder] method
/// for use in constructing the form field's widget.
Matt Perry's avatar
Matt Perry committed
408
class FormFieldState<T> extends State<FormField<T>> {
409 410
  T? _value;
  String? _errorText;
411
  bool _hasInteractedByUser = false;
Matt Perry's avatar
Matt Perry committed
412 413

  /// The current value of the form field.
414
  T? get value => _value;
Matt Perry's avatar
Matt Perry committed
415

416 417 418
  /// The current validation error returned by the [FormField.validator]
  /// callback, or null if no errors have been triggered. This only updates when
  /// [validate] is called.
419
  String? get errorText => _errorText;
Matt Perry's avatar
Matt Perry committed
420 421 422 423

  /// True if this field has any validation errors.
  bool get hasError => _errorText != null;

424 425 426 427 428 429 430 431 432 433
  /// True if the current value is valid.
  ///
  /// This will not set [errorText] or [hasError] and it will not update
  /// error display.
  ///
  /// See also:
  ///
  ///  * [validate], which may update [errorText] and [hasError].
  bool get isValid => widget.validator?.call(_value) == null;

Matt Perry's avatar
Matt Perry committed
434 435
  /// Calls the [FormField]'s onSaved method with the current value.
  void save() {
436
    widget.onSaved?.call(value);
Matt Perry's avatar
Matt Perry committed
437 438 439 440 441
  }

  /// Resets the field to its initial value.
  void reset() {
    setState(() {
442
      _value = widget.initialValue;
443
      _hasInteractedByUser = false;
Matt Perry's avatar
Matt Perry committed
444 445
      _errorText = null;
    });
446
    Form.of(context)?._fieldDidChange();
Matt Perry's avatar
Matt Perry committed
447 448
  }

449 450
  /// Calls [FormField.validator] to set the [errorText]. Returns true if there
  /// were no errors.
451 452 453 454 455
  ///
  /// See also:
  ///
  ///  * [isValid], which passively gets the validity without setting
  ///    [errorText] or [hasError].
456 457 458 459 460 461 462
  bool validate() {
    setState(() {
      _validate();
    });
    return !hasError;
  }

463
  void _validate() {
464
    if (widget.validator != null)
465
      _errorText = widget.validator!(_value);
466 467
  }

Matt Perry's avatar
Matt Perry committed
468
  /// Updates this field's state to the new value. Useful for responding to
469 470
  /// child widget changes, e.g. [Slider]'s [Slider.onChanged] argument.
  ///
471 472 473
  /// Triggers the [Form.onChanged] callback and, if [Form.autovalidateMode] is
  /// [AutovalidateMode.always] or [AutovalidateMode.onUserInteraction],
  /// revalidates all the fields of the form.
474
  void didChange(T? value) {
Matt Perry's avatar
Matt Perry committed
475 476
    setState(() {
      _value = value;
477
      _hasInteractedByUser = true;
Matt Perry's avatar
Matt Perry committed
478 479 480 481
    });
    Form.of(context)?._fieldDidChange();
  }

482 483
  /// Sets the value associated with this form field.
  ///
484
  /// This method should only be called by subclasses that need to update
485 486
  /// the form field value due to state changes identified during the widget
  /// build phase, when calling `setState` is prohibited. In all other cases,
487
  /// the value should be set by a call to [didChange], which ensures that
488 489
  /// `setState` is called.
  @protected
490
  void setValue(T? value) {
491 492 493
    _value = value;
  }

Matt Perry's avatar
Matt Perry committed
494 495 496
  @override
  void initState() {
    super.initState();
497
    _value = widget.initialValue;
Matt Perry's avatar
Matt Perry committed
498 499 500 501 502 503 504 505 506 507
  }

  @override
  void deactivate() {
    Form.of(context)?._unregister(this);
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
508 509 510 511 512 513 514 515 516 517 518 519 520 521
    if (widget.enabled) {
      switch (widget.autovalidateMode) {
        case AutovalidateMode.always:
          _validate();
          break;
        case AutovalidateMode.onUserInteraction:
          if (_hasInteractedByUser) {
            _validate();
          }
          break;
        case AutovalidateMode.disabled:
          break;
      }
    }
Matt Perry's avatar
Matt Perry committed
522
    Form.of(context)?._register(this);
523
    return widget.builder(this);
Matt Perry's avatar
Matt Perry committed
524
  }
525
}
526 527 528 529 530 531 532 533 534 535 536 537 538

/// Used to configure the auto validation of [FormField] and [Form] widgets.
enum AutovalidateMode {
  /// No auto validation will occur.
  disabled,

  /// Used to auto-validate [Form] and [FormField] even without user interaction.
  always,

  /// Used to auto-validate [Form] and [FormField] only after each user
  /// interaction.
  onUserInteraction,
}