Created
August 5, 2020 02:54
-
-
Save 5lineofcode/1a7e6d7908688805649917d04472f528 to your computer and use it in GitHub Desktop.
Flutter Dynamic Form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: MyWidget(), | |
), | |
), | |
); | |
} | |
} | |
class MyWidget extends StatelessWidget { | |
Map formDefinitions = { | |
"form_name": "Form Product", | |
"fields": [ | |
{ | |
"field_name": "Product Name", | |
"type": "textfield", | |
}, | |
{ | |
"field_name": "Price", | |
"type": "numberfield", | |
}, | |
{ | |
"field_name": "Description", | |
"type": "textarea", | |
} | |
], | |
}; | |
Widget getUiFieldWidget(field) { | |
switch(field["type"]){ | |
case "textfield": | |
return TextField( | |
decoration: InputDecoration( | |
hintText: '', | |
labelText: field["field_name"] | |
), | |
); | |
break; | |
case "numberfield": | |
return TextField( | |
decoration: InputDecoration( | |
hintText: '', | |
labelText: field["field_name"] | |
), | |
keyboardType: TextInputType.number | |
); | |
break; | |
case "textarea": | |
return TextField( | |
decoration: InputDecoration( | |
hintText: '', | |
labelText: field["field_name"] | |
), | |
maxLines: 4, | |
); | |
break; | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
var formFields = formDefinitions["fields"]; | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(formDefinitions["form_name"]), | |
), | |
body: Container( | |
padding: EdgeInsets.all(10.0), | |
child: ListView.builder( | |
itemCount: formFields.length, | |
itemBuilder: (context, index) { | |
var field = formFields[index]; | |
return getUiFieldWidget(field); | |
}, | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment