Create Dynamic TextFormFields in Flutter

Saujan Bindukar
2 min readJun 15, 2021

Do you want to create multiple text form fields, remove them and retrieve the value from the text form fields?

This article will help you to create multiple TextFormFields, remove them and retrieve the value from TextFormFields.

Step 1: Create a Flutter Project.

Step 2: Create a Stateful Widget class.

Step 3: Inside the stateful widget class, declare the empty list of String.

List<String> newTextField = [];

This is used to store the values of the TextFormFields.

Step 4: Create a TextFormField with a plus icon in a Row.

Row(children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration: InputDecoration(
hintText: 'First Text field',))),),
IconButton(
onPressed: () {},
icon: Icon(Icons.add_circle,
color: Colors.green,
size: 30),)
],
),

Step 4: Add an empty value in the newTextField list after pressing add icon.

onPressed: ()
{
setState(() {
newTextField.add('');
});
},

Now, What after adding the empty value to the list? Let’s generate the new TextFormFields.

Step 5: Create a method getNewTextFormFields to generate the new TextFormField with a remove icon to remove the TextFormField.

List<Widget> getNewTextFormFields() {
var textField = <Widget>[];
for (var i = 0; i < newTextField.length; i++) {
textField.add(
Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
onChanged: (value) {
newTextField[i] = value;
},
decoration: InputDecoration(
hintText: '${i + 1} Text field',
),
),
),
),
//Removing the TextFormField
IconButton(
onPressed: () {
setState(() {
newTextField.removeAt(i);
});
},
icon: Icon(
Icons.remove_circle,
color: Colors.red,
size: 30,
),
)
],
),
);
}
return textField;
}

Now, we have to display the newly generated widget on the screen.

Step 6: Spread the method getNewTextFormFields() inside the body of stateful widget class.

...getNewTextFormFields(),

Step 7: Create a button to print the values.

///Button to print the values
ElevatedButton(
onPressed: () {
//the valued are displayed in the list
print(newTextField);
},
child: Text('Submit'),
),

Finally, we’ll get the value of each TextFormFields in the form of a list.

Get the full code snippet from here.

--

--