Dynamic Forms using Flutter ListView
When it comes to developers, automating repetitive code can highly influence the development process by increasing the speed of delivery and save a lot of time.
One of the concepts that I love utilizing when experimenting with Flutter is code resusability and this is by using logic to convert a manual idea dynamically.
Use Case
Let’s create a basic sign up form with 3 fields and a button.
- Username field
- Password field
- Submit button
Create a List of items
This list represents a few attributes of the 3 fields above, mainly the label and obscure flag.
Widget dependency
The 3 fields constitute 2 TextFormFields and 1 RaisedButton. The TextFormFields require controllers to access what is inserted by the user. This will be implementd dynamically with the code below.
ListView implementation
Let’s use the Listview.builder that builds the children on demand. The basic code looks like this:
Inside the constructor, we’ll add a condition that assists in positioning the 3 fields accordingly. For instance, the button should be positioned after the 2 TextFormFields are displayed as shown below:
Adding to the above existing code, the rest of items, which are the 2 fields (username and password) will then fall into the else part of the statement as shown below:
The ListView is complete and can be injected into the Scaffold body. We only need to add a small portion of code. When onPressed() method is executed, let’s print what the user has inserted from the 2 TextFormFields as shown:
You can find the full source code here. I hope the article helps you solve more complex lists in an easier way.
Happy coding.