Created
December 31, 2019 21:13
-
-
Save MillerAdulu/87ca63e3b1ee847c1fbca775289a8e5a to your computer and use it in GitHub Desktop.
Dynamic Generation of Form Fields Based on Database Values
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
// Assumption is, all the fields hold the same kind of value | |
// An entry from the database together with the ID | |
class Measurement { | |
final int id; | |
final String name; | |
Measurement({this.id, this.name}); | |
} | |
// Field Instance class defines the variables that will be used for each field | |
class FieldInstance { | |
// Controller to manage how text is edited | |
final TextEditingController controller; | |
final BehaviorSubject<String> subject; | |
// Measurement a class instance that holds one entry from the | |
//database and it's ID | |
final Measurement measurement; | |
final Function(String) onChanged; | |
final Stream<String> value; | |
FieldInstance({ | |
this.controller, | |
this.subject, | |
this.measurement, | |
this.onChanged, | |
this.value, | |
}); | |
} | |
// Assuming you have fetched your list from the database and | |
// formatted it to sth fancy | |
var measurements = [Measurement(id: 21, name: "Hips"), | |
Measurement(id: 1, name: "Neck"), | |
Measurement(id: 2, name: "Shoulders") | |
]; | |
final _subject = BehaviorSubject<String>(); | |
// Loop through the measurements, in your case engines | |
// and create an array of field instances | |
final fields = measurements.map((measurement) => FieldInstance( | |
controller: TextEditingController(), | |
subject: _subject, | |
measurement: measurement, | |
onChanged: _subject.sink.add, | |
value: _subject.stream, | |
)).toList(); | |
// Finally in the Widget, loop through the fields and create the form | |
... | |
Column(children: [ | |
// Generate a list of widgets for the column and spread (...) them | |
...fields.map((field) => TextFormField( | |
controller: field.controller, | |
onChanged: field.onChanged, | |
decoration: InputDecoration( | |
labelText: field.measurement.name, | |
labelStyle: TextStyle( | |
color: formLabel, | |
), | |
errorText: snapshot.error, | |
), | |
)).toList(), | |
]), |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment