reactive_forms
reactive_forms copied to clipboard
FormArray with FormGrop(s) dont work with .patchValue()
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:
- explain how to use FormArray of FormGroups correctly;
- 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',
),
],
),
],
);
},
),
),
));
}
}