Home > Net >  Use different textfield controller in listview builder
Use different textfield controller in listview builder

Time:11-07

I've create a TextField inside a ListView.builder. When user tap the button, it will add the new TextField. How do I use different TextField controller inside a ListView.builder? Thanks.

codes

ListView.builder(
    physics: NeverScrollableScrollPhysics(),
    shrinkWrap: true,
    itemCount: categoryCount,
    itemBuilder: (context, index) {
      return TextField(
        // controller: 
        decoration: InputDecoration(
          hintText: 'Amount',
          border: InputBorder.none,
          focusedBorder: InputBorder.none,
          enabledBorder: InputBorder.none,
          errorBorder: InputBorder.none,
          disabledBorder: InputBorder.none,
        ),
      );
    });

CodePudding user response:

You can create a list of TextFieldController and access each one with index passed as parameter in itemBuilder function

CodePudding user response:

Try This answer hope its helpful to you. and try below answer also. you used Stateful Widget

Create variables

var name = <TextEditingController>[];
var cards = <Card>[];

Create init() function

 @override
  void initState() {
    super.initState();
    cards.add(createCard());
  }

Create method for createing TextEditingController

  createCard() {
    var nameController = TextEditingController();
    name.add(nameController);
    return Card(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          TextField(
            controller: nameController,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: ' Name',
              hintText: 'Add Name',
            ),
          ),
        ],
      ),
    );
  }

Create your Widget:

Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: cards.length,
              itemBuilder: (BuildContext context, int index) {
                return cards[index];
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: ElevatedButton(
              child: Text('Add'),
              onPressed: () => setState(
                () => cards.add(
                  createCard(),
                ),
              ),
            ),
          )
        ],
      ),
  • Related