Dynamic Forms using Flutter ListView

Mobterest Studio
3 min readFeb 11, 2021

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.

  1. Username field
  2. Password field
  3. 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.

Dynamic generation of TextEditingControllers

ListView implementation

Let’s use the Listview.builder that builds the children on demand. The basic code looks like this:

ListView.builder constructor

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:

Positioning of the Submit button dynamically

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:

Positioning of TextFormFields dynamically

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:

OnPressed() method

You can find the full source code here. I hope the article helps you solve more complex lists in an easier way.

Happy coding.

--

--

No responses yet