Flutter add more fields in a form

1.7k Views Asked by At

I am creating a form in flutter that will be used to capture data. One area of the capture form should be able to capture more than one entry. How can I use a button to add more fields so that it is possible for a user to enter more that one entry . This is the part of the form

  _Details() {
    return Column(
      children: <Widget>[
        Container(
          alignment: Alignment.center,
          width: double.infinity,
          color: Theme.of(context).accentColor,
          padding: const EdgeInsets.all(8.0),
          child: Text("Details "),
        ),
        SizedBox(
          height: 5.0,
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            // crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              TextFormField(
                controller: _bankController,
                decoration: InputDecoration(
                  hintText: 'Name',
                ),
              ),
              SizedBox(
                height: 5.0,
              ),
              TextFormField(
                controller: _bankController,
                decoration: InputDecoration(
                  hintText: 'Branch',
                ),
              )              
            ],
          ),
        ),
      ],
    );
  }
1

There are 1 best solutions below

1
On

first make a model class like this

    class TextFieldClass{
      TextEditingController controller = new TextEditingController();
      var hint;
    
      TextFieldClass({this.controller,this.hint});
    }

then you just have to make a listview and call a widget function whereever you want, like this

      List<TextFieldClass> textFields = [];
    
      Widget list(){
        return Container(
          padding:EdgeInsets.symmetric(vertical: 10),
          
          child: ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: textFields.length,
              itemBuilder: (context,index){
                return Padding(
                    padding: EdgeInsets.symmetric(vertical: 5),
    
                    child:TextFormField(
                      controller: textFields[index].controller,
                      decoration: InputDecoration(
                        hintText:textFields[index].hint,
                      ),
                    )
                );
              }),
        );
      }

now the last part you just have to add items in list For example you make a add button and in add's button onTap function you will write

 textFields.add(TextFieldClass(
  controller: newController,
  hint: 'new field'
));