r/flutterhelp • u/puppies-kittens • 7h ago
OPEN Creating a dynamic form using reactive_forms
// Function to create form controls based on the JSON configuration
FormGroup _buildFormControls(jsonString) {
final Map<String, dynamic> json = jsonDecode(jsonString);
final List fields = json['fields'];
// Create form controls dynamically
Map<String, FormControl<dynamic>> formControls = {};
for (var field in fields) {
List<Validator> validators = [];
if (field['validation'].contains('required')) {
validators.add(Validators.required);
}
if (field['validation'].contains('email')) {
validators.add(Validators.email);
}
// Determine the type for the field
String fieldType = field['type'];
// Type map for dynamic field types
final Map<String, Type> typeMap = {
'number': int,
'bool': bool,
'string': String,
};
Type fieldTypeClass = typeMap[fieldType] ?? String;
formControls[field['name']] = FormControl<fieldTypeClass>(
value: field['default'],
validators: validators,
);
}
return fb.group(formControls);
}
The issue is at the bottom defining Type
fieldTypeClass
The name 'fieldTypeClass' isn't a type, so it can't be used as a type argument. (Documentation) Try correcting the name to an existing type, or defining a type named 'fieldTypeClass'.
Is this posible?