Dynamic forms in flutter #987
-
I am creating an app where user have to fill the form based on the assignments given to him. the admin will give him the assignments whose fields may be dynamic means the admin can create new fields and create the task. Now this task will be given to the user through firebase. Now I want to know that how to create form in the flutter app and give back the details. The fields may be a table, a image , string, number etc., I had thought that I can create all fields in the array or a json in firebase. It is somewhat similar to google forms.but didn't figure it out. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
One possible sollution is to assign a "string-key" for every field that your app supports, then map every field in that json into it's corrisponding widget with its parameters. If your json looks like this: [
{
"type": "text_field",
"label": "text field1",
"value": "your value here",
"hintText": "custom hint",
"errorText": "custom error"
},
{
"type": "text_area",
"label": "text field2",
"hintText": "custom hint",
"errorText": "custom error"
},
{
"type": "check_box",
"label": "text field2",
"value": ""
}
] Then your code should look like this: // Maps every object in the json to an instance of a widget
static final Map<String, Widget Function(Map<String, dynamic>)> _widgetsMap =
{
'text_field': _buildTextField,
'text_area': _buildTextField,
'check_box': _buildCheckBox,
// etc...
};
// Holds controllers created for each field
static List controllers = [];
// Holds iterating logic on each json objects
static FormBuilder mapJsonToForm(List<Map<String, dynamic>> json) {
List<Widget> formList = [];
json.forEach((fieldDetails) {
final type = fieldDetails['type'];
if (_widgetsMap.containsKey(type))
formList.add(_widgetsMap[type]!(fieldDetails));
});
return FormBuilder(
child: Column(
children: formList,
),
);
}
static Widget _buildTextField(Map<String, dynamic> fieldDetails) {
final TextEditingController controller =
TextEditingController(text: fieldDetails['value']);
controllers..add(controller);
return TextField(
controller: controller,
decoration: InputDecoration(
labelText: fieldDetails['label'],
hintText: fieldDetails['hintText'],
errorText: fieldDetails['errorText'],
border: OutlineInputBorder(),
),
);
} |
Beta Was this translation helpful? Give feedback.
One possible sollution is to assign a "string-key" for every field that your app supports, then map every field in that json into it's corrisponding widget with its parameters.
If your json looks like this:
Then your code should look like this: