How to create a distinct TextEditingControllers per item in a list?

781 views Asked by At

I have a list of widgets as follows, with a controller variable for user input in a TextField:

final List<Widget> _setsList = [];
TextEditingController repsController = TextEditingController

I am pushing a new widget 'createSetCard' below when the user presses a button and saving their input in the TextEditingController:

Widget createSetCard() {
  return Row(
    children: [
      Expanded(
        child: Container(
          height: 60,
          alignment: Alignment.center,
          child: Text(
            setNumber.toString(),
            style: const TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
          decoration: const BoxDecoration(color: constants.kHunterColor),
        ),
      ),
      Expanded(
        flex: 3,
        child: TextField(
          controller:repsController,
          enabled: tf,
          textAlign: TextAlign.center,
          maxLength: 3,
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(
            isDense: true,
            contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
            hintText: "reps",
            // suffix: Text('reps'),
            counterText: "",
            border: InputBorder.none,
          ),
        ),
      ),
      const Expanded(
        child: Center(child: Text("x")),
      ),
      Expanded(
        flex: 3,
        child: TextField(
          controller: lbsController,
          textAlign: TextAlign.center,
          maxLength: 3,
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(
            isDense: true,
            contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
            hintText: "lbs",
            suffix: Text("lbs"),
            counterText: "",
            border: InputBorder.none,
            //suffix: Text('lbs'),
          ),
        ),
      ),
    ],
  );
}

My question is when I have multiple items being displayed in my ListView, each of the items changes when I change one of the input fields. How can I make each input field separate from one another in the List? As shown below, each TextField in the ListView is being edited when I change any value of any item in the list.

enter image description here

1

There are 1 answers

1
mehdi31075 On

You should create a list of TextEditingController in your controller:

List<TextEditingController> textEditingControllers = [].obs;