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

5 6
// @dart = 2.8

7
import 'framework.dart';
8
import 'navigator.dart';
9
import 'will_pop_scope.dart';
10

11
/// An optional container for grouping together multiple form field widgets
12
/// (e.g. [TextField] widgets).
13 14 15 16 17 18 19
///
/// 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].
20
///
21
/// {@tool dartpad --template=stateful_widget_scaffold}
22 23 24 25 26
/// This example shows a [Form] with one [TextFormField] to enter an email
/// address and a [RaisedButton] to submit the form. A [GlobalKey] is used here
/// to identify the [Form] and validate input.
///
/// ![](https://flutter.github.io/assets-for-api-docs/assets/widgets/form.png)
27 28 29 30 31 32 33 34 35 36 37 38
///
/// ```dart
/// final _formKey = GlobalKey<FormState>();
///
/// @override
/// Widget build(BuildContext context) {
///   return Form(
///     key: _formKey,
///     child: Column(
///       crossAxisAlignment: CrossAxisAlignment.start,
///       children: <Widget>[
///         TextFormField(
39 40 41
///           decoration: const InputDecoration(
///             hintText: 'Enter your email',
///           ),
42 43 44 45
///           validator: (value) {
///             if (value.isEmpty) {
///               return 'Please enter some text';
///             }
46
///             return null;
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
///           },
///         ),
///         Padding(
///           padding: const EdgeInsets.symmetric(vertical: 16.0),
///           child: RaisedButton(
///             onPressed: () {
///               // Validate will return true if the form is valid, or false if
///               // the form is invalid.
///               if (_formKey.currentState.validate()) {
///                 // Process data.
///               }
///             },
///             child: Text('Submit'),
///           ),
///         ),
///       ],
///     ),
///   );
/// }
/// ```
/// {@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].
74
class Form extends StatefulWidget {
75 76 77
  /// Creates a container for form fields.
  ///
  /// The [child] argument must not be null.
78
  const Form({
79
    Key key,
80
    @required this.child,
81
    this.autovalidate = false,
82
    this.onWillPop,
83
    this.onChanged,
84
    AutovalidateMode autovalidateMode,
85
  }) : assert(child != null),
86 87 88 89 90 91 92 93 94
       assert(autovalidate != null),
       assert(
         autovalidate == false ||
         autovalidate == true && autovalidateMode == null,
         'autovalidate and autovalidateMode should not be used together.'
       ),
       autovalidateMode = autovalidate
           ? AutovalidateMode.always
           : (autovalidateMode ?? AutovalidateMode.disabled),
95
       super(key: key);
96

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

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

117 118 119 120 121
  /// If true, form fields will validate and update their error text
  /// immediately after every change. Otherwise, you must call
  /// [FormState.validate] to validate.
  final bool autovalidate;

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

134 135 136 137 138 139
  /// 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;

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

146
  @override
147
  FormState createState() => FormState();
148 149
}

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

161 162
  // 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
163
  void _fieldDidChange() {
164 165
    if (widget.onChanged != null)
      widget.onChanged();
166 167 168 169


    _hasInteractedByUser = _fields
        .any((FormFieldState<dynamic> field) => field._hasInteractedByUser);
170 171 172 173
    _forceRebuild();
  }

  void _forceRebuild() {
174
    setState(() {
Matt Perry's avatar
Matt Perry committed
175
      ++_generation;
176 177 178
    });
  }

Matt Perry's avatar
Matt Perry committed
179 180 181 182 183 184 185 186
  void _register(FormFieldState<dynamic> field) {
    _fields.add(field);
  }

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

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

202
    return WillPopScope(
203
      onWillPop: widget.onWillPop,
204
      child: _FormScope(
205 206
        formState: this,
        generation: _generation,
207
        child: widget.child,
208
      ),
209 210 211
    );
  }

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

218
  /// Resets every [FormField] that is a descendant of this [Form] back to its
219
  /// [FormField.initialValue].
220 221 222
  ///
  /// The [Form.onChanged] callback will be called.
  ///
223 224
  /// 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
225
  void reset() {
226
    for (final FormFieldState<dynamic> field in _fields)
Matt Perry's avatar
Matt Perry committed
227
      field.reset();
228
    _hasInteractedByUser = false;
Matt Perry's avatar
Matt Perry committed
229 230
    _fieldDidChange();
  }
231

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

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

Matt Perry's avatar
Matt Perry committed
250
class _FormScope extends InheritedWidget {
251
  const _FormScope({
252 253
    Key key,
    Widget child,
Matt Perry's avatar
Matt Perry committed
254
    FormState formState,
255
    int generation,
256
  }) : _formState = formState,
257 258 259
       _generation = generation,
       super(key: key, child: child);

Matt Perry's avatar
Matt Perry committed
260
  final FormState _formState;
261 262 263 264 265

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

266
  /// The [Form] associated with this widget.
267
  Form get form => _formState.widget;
268

Matt Perry's avatar
Matt Perry committed
269 270 271 272 273
  @override
  bool updateShouldNotify(_FormScope old) => _generation != old._generation;
}

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

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

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

291 292 293 294
/// 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
295 296 297 298 299 300 301 302
///
/// 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.
///
303 304 305 306 307
/// 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.
///
308 309 310 311
/// 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
312
class FormField<T> extends StatefulWidget {
313 314 315
  /// Creates a single form field.
  ///
  /// The [builder] argument must not be null.
316
  const FormField({
Matt Perry's avatar
Matt Perry committed
317 318 319 320 321
    Key key,
    @required this.builder,
    this.onSaved,
    this.validator,
    this.initialValue,
322
    this.autovalidate = false,
323
    this.enabled = true,
324
    AutovalidateMode autovalidateMode,
325
  }) : assert(builder != null),
326 327 328 329 330 331 332 333
       assert(
         autovalidate == false ||
         autovalidate == true && autovalidateMode == null,
         'autovalidate and autovalidateMode should not be used together.'
       ),
       autovalidateMode = autovalidate
           ? AutovalidateMode.always
           : (autovalidateMode ?? AutovalidateMode.disabled),
334
       super(key: key);
335

Matt Perry's avatar
Matt Perry committed
336
  /// An optional method to call with the final value when the form is saved via
337
  /// [FormState.save].
Matt Perry's avatar
Matt Perry committed
338 339 340 341
  final FormFieldSetter<T> onSaved;

  /// An optional method that validates an input. Returns an error string to
  /// display if the input is invalid, or null otherwise.
342 343 344 345
  ///
  /// The returned value is exposed by the [FormFieldState.errorText] property.
  /// The [TextFormField] uses this to override the [InputDecoration.errorText]
  /// value.
346 347 348 349 350 351 352
  ///
  /// 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
  /// height parent like [SizedBox], or set the [TextFormField.helperText]
  /// parameter to a space.
Matt Perry's avatar
Matt Perry committed
353 354 355 356 357 358 359 360 361
  final FormFieldValidator<T> validator;

  /// 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.
  final T initialValue;
362

363
  /// If true, this form field will validate and update its error text
364 365
  /// immediately after every change. Otherwise, you must call
  /// [FormFieldState.validate] to validate. If part of a [Form] that
366
  /// auto-validates, this value will be ignored.
367 368
  final bool autovalidate;

369 370
  /// Whether the form is able to receive user input.
  ///
371 372 373
  /// 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].
374 375
  final bool enabled;

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
  /// Used to enable/disable this form field auto validation and update its
  /// error text.
  ///
  /// {@template flutter.widgets.form.autovalidateMode}
  /// 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.
  ///
  /// Defaults to [AutovalidateMode.disabled] if [autovalidate] is false which
  /// means no auto validation will occur. If [autovalidate] is true then this
  /// is set to [AutovalidateMode.always] for backward compatibility.
  /// {@endtemplate}
  final AutovalidateMode autovalidateMode;

391
  @override
392
  FormFieldState<T> createState() => FormFieldState<T>();
Matt Perry's avatar
Matt Perry committed
393 394
}

395 396
/// 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
397 398 399
class FormFieldState<T> extends State<FormField<T>> {
  T _value;
  String _errorText;
400
  bool _hasInteractedByUser = false;
Matt Perry's avatar
Matt Perry committed
401 402 403 404

  /// The current value of the form field.
  T get value => _value;

405 406 407
  /// 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.
Matt Perry's avatar
Matt Perry committed
408 409 410 411 412
  String get errorText => _errorText;

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

413 414 415 416 417 418 419 420 421 422
  /// 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
423 424
  /// Calls the [FormField]'s onSaved method with the current value.
  void save() {
425 426
    if (widget.onSaved != null)
      widget.onSaved(value);
Matt Perry's avatar
Matt Perry committed
427 428 429 430 431
  }

  /// Resets the field to its initial value.
  void reset() {
    setState(() {
432
      _value = widget.initialValue;
433
      _hasInteractedByUser = false;
Matt Perry's avatar
Matt Perry committed
434 435
      _errorText = null;
    });
436
    Form.of(context)?._fieldDidChange();
Matt Perry's avatar
Matt Perry committed
437 438
  }

439 440
  /// Calls [FormField.validator] to set the [errorText]. Returns true if there
  /// were no errors.
441 442 443 444 445
  ///
  /// See also:
  ///
  ///  * [isValid], which passively gets the validity without setting
  ///    [errorText] or [hasError].
446 447 448 449 450 451 452
  bool validate() {
    setState(() {
      _validate();
    });
    return !hasError;
  }

453
  void _validate() {
454 455
    if (widget.validator != null)
      _errorText = widget.validator(_value);
456 457
  }

Matt Perry's avatar
Matt Perry committed
458
  /// Updates this field's state to the new value. Useful for responding to
459 460
  /// child widget changes, e.g. [Slider]'s [Slider.onChanged] argument.
  ///
461 462 463
  /// Triggers the [Form.onChanged] callback and, if [Form.autovalidateMode] is
  /// [AutovalidateMode.always] or [AutovalidateMode.onUserInteraction],
  /// revalidates all the fields of the form.
464
  void didChange(T value) {
Matt Perry's avatar
Matt Perry committed
465 466
    setState(() {
      _value = value;
467
      _hasInteractedByUser = true;
Matt Perry's avatar
Matt Perry committed
468 469 470 471
    });
    Form.of(context)?._fieldDidChange();
  }

472 473 474 475 476
  /// Sets the value associated with this form field.
  ///
  /// This method should be only be called by subclasses that need to update
  /// the form field value due to state changes identified during the widget
  /// build phase, when calling `setState` is prohibited. In all other cases,
477
  /// the value should be set by a call to [didChange], which ensures that
478 479 480 481 482 483
  /// `setState` is called.
  @protected
  void setValue(T value) {
    _value = value;
  }

Matt Perry's avatar
Matt Perry committed
484 485 486
  @override
  void initState() {
    super.initState();
487
    _value = widget.initialValue;
Matt Perry's avatar
Matt Perry committed
488 489 490 491 492 493 494 495 496 497
  }

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

  @override
  Widget build(BuildContext context) {
498 499 500 501 502 503 504 505 506 507 508 509 510 511
    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
512
    Form.of(context)?._register(this);
513
    return widget.builder(this);
Matt Perry's avatar
Matt Perry committed
514
  }
515
}
516 517 518 519 520 521 522 523 524 525 526 527 528

/// 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,
}