patchValue method

  1. @override
void patchValue(
  1. List<T?>? value, {
  2. bool updateParent = true,
  3. bool emitEvent = true,
})
override

Patches the value of the FormArray. It accepts an array that matches the structure of the control, and does its best to match the values to the correct controls in the array.

It accepts both super-sets and sub-sets of the array without throwing an error.

The argument value is the array of latest values for the controls.

When updateParent is true or not supplied (the default) each change affects this control and its parent, otherwise only affects to this control.

When emitEvent is true or not supplied (the default), both the statusChanges and valueChanges emit events with the latest status and value when the control is reset. When false, no events are emitted.

Example

Patch with a sub-set array

final array = FormArray<int>([
  FormControl<int>(value: 1),
  FormControl<int>(value: 2),
  FormControl<int>(value: 3),
]);

print(array.value); // outputs: [1, 2, 3]

array.patchValue([4]);

print(array.value); // outputs: [4, 2, 3]

Example

Patch with a super-set array

final array = FormArray<int>([
  FormControl<int>(value: 1),
  FormControl<int>(value: 2),
]);

print(array.value); // outputs: [1, 2]

array.patchValue([3, 4, 5]);

print(array.value); // outputs: [3, 4]

Implementation

@override
void patchValue(
  List<T?>? value, {
  bool updateParent = true,
  bool emitEvent = true,
}) {
  if (value == null) {
    return;
  }

  for (var i = 0; i < value.length; i++) {
    if (i < _controls.length) {
      _controls[i].patchValue(
        value[i] as T,
        updateParent: false,
        emitEvent: emitEvent,
      );
    }
  }

  updateValueAndValidity(
    updateParent: updateParent,
    emitEvent: emitEvent,
  );
}