reactive_forms icon indicating copy to clipboard operation
reactive_forms copied to clipboard

FormArray with FormGrop(s) dont work with .patchValue()

Open ShyshkovOleg opened this issue 9 months ago • 0 comments

Hi, @joanpablo. Thanks for you package it is great. Im facing one issue with FormArray of FormGroups. .patchValue() did not patch and .updateValue() throws an error. Could you please:

  1. explain how to use FormArray of FormGroups correctly;
  2. could I use FormControl instead of FormControlName with FormArray of FormGroups
class _NotificationsState extends State<Notifications> {
  FormGroup optionForm =
      FormGroup({'options': FormArray<Map<String, dynamic>>([])});

  FormArray get optionsFormArray {
    return optionForm.control('options') as FormArray;
  }
  @override
  void initState() {
    optionForm.patchValue({
      'options': [
        {'name': "option #1", 'value': '#1 value'},
        {'name': "option #2", 'value': '#2 value'}
      ]
    });

    /// <----- []
    print("patch->>${optionsFormArray.value}");

    optionForm.updateValue({
      'options': [
        {'name': "option #1", 'value': '#1 value'},
        {'name': "option #2", 'value': '#2 value'}
      ]
    });

    /// <----- [{name: option #1, value: #1 value}, {name: option #2, value: #2 value}]
    /// Get an ERROR: FormControlNotFoundException: control with name: '0.name' not found.
    print("update->>${optionsFormArray.value}");

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<MyColors>()!;

    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          color: colors.baseDarkBg,
          width: double.infinity,
          height: double.infinity,
          child: ReactiveForm(
            formGroup: optionForm,
            child: ReactiveFormArray(
              formArray: optionsFormArray,
              builder: (context, formArray, child) {
                return Column(
                  children: [
                    for (int i = 0; i < formArray.controls.length; i++)
                      Column(
                        children: [
                          ReactiveTextField(
                            formControlName: '$i.name',
                          ),
                          ReactiveTextField(
                            formControlName: '$i.value',
                          ),
                        ],
                      ),
                  ],
                );
              },
            ),
          ),
        ));
  }
}

ShyshkovOleg avatar May 14 '24 09:05 ShyshkovOleg