reactive_forms Flutter - creating and rendering Groups

1.1k views Asked by At

Having difficulty figuring how to render groups as their example (https://github.com/joanpablo/reactive_forms#groups-of-groups-grin):

final form = FormGroup({
  'personal': FormGroup({
    'name': FormControl<String>(validators: [Validators.required]),
    'email': FormControl<String>(validators: [Validators.required]),
  }),
  'phone': FormGroup({
    'phoneNumber': FormControl<String>(validators: [Validators.required]),
    'countryIso': FormControl<String>(validators: [Validators.required]),
  }),
  'address': FormGroup({
    'street': FormControl<String>(validators: [Validators.required]),
    'city': FormControl<String>(validators: [Validators.required]),
    'zip': FormControl<String>(validators: [Validators.required]),
  }),
});

Im using

ReactiveTextField(formControlName: 'personal', ),

but throws error:

Expected a value of type 'FormControl<dynamic>', but got one of type 'FormGroup'

My aim is to get output like below:

{
  "personal": {
    "name": "...",
    "email": "..."
  },
  "phone": {
    "phoneNumber": "...",
    "countryIso": "..."
  },
  "address": {
    "street": "...",
    "city": "...",
    "zip": "..."
  }
}

Any guidance and advice is much appreciated!

1

There are 1 answers

0
Effie On

Got advice from joanpablo (https://github.com/joanpablo)

Below syntax can be used:

ReactiveTextField(formControlName: 'personal.name', ),

The above code is in case you have for example a ReactiveForm (or a ReactiveFormBuilder) and as a child you have this ReactiveTextField:

ReactiveForm(
   formGroup: form,
   child: Column(children: [
      ReactiveTextField(
         formControlName: 'personal.name', 
      ),
   ]),
),

But you can also have nested ReactiveForm widgets:

ReactiveForm(
   formGroup: form,
   child: Column(children: [
      ReactiveForm(
         formGroup: form.control('personal') as FormGroup,
            child: Column(children: [
               ReactiveTextField(
                  formControlName: 'name', 
               ),
            ]),
         ),
   ]),
),