8

I'm trying to make it possible to edit a list of strings. The problem is, when I delete a list item via the IconButton, the TextField rebuilds but somehow still has the old value. With debugging I see, that my List of Strings are however updated correctly, meaning the deleted String is actually being deleted in my list.

This is my code:

class EditInfoItemDialog extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => _EditInfoitemDialogState();
}

class _EditInfoitemDialogState extends State<EditInfoItemDialog> {

  final _formKey = GlobalKey<FormState>();
  List<String> values = ['A', 'B', 'C'];

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        child: Column(
          children: <Widget>[
            ...values.asMap().map((int index, String point) {
              return MapEntry(index, Row(
                children: [
                  Text(index.toString()),
                  Expanded(
                    child: TextFormField(
                      decoration: InputDecoration(hintText: 'Info'),
                      initialValue: values[index],
                      onChanged: (value) => setState(() {values[index] = value; }),
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.delete),
                    color: Colors.red,
                    onPressed: () {
                      setState(() {
                        values.removeAt(index);
                        print(values);
                      });
                    },
                  )
                ]
              ));
            }).values.toList(),
            FlatButton(
              child: Text('Add Bulletpoint'),
              onPressed: () {
                setState(() {
                  if (values == null) values = [];
                  values.add('');
                });
              },
            )
          ],
        ),
      ),
    );

  }

Any Ideas?

Jonas
  • 7,089
  • 15
  • 49
  • 110

1 Answers1

14

You need to add a key to your TextFormField like this:

key: ObjectKey(values[index])

Here is an explanation and an example with the reason why you need to add a key in this case: What are Keys in the Stateless widgets class?

Key is something used by flutter engine at the step of recognizing which widget in a list as changed

More info: key property

Pablo Barrera
  • 10,387
  • 3
  • 28
  • 49
  • Ok I fixed it, I shouldn't do `setState` in the onChange of the TextField – Jonas Oct 12 '19 at 09:11
  • Is this a problem if two widgets have the same key? If I have two TextFormField and someone enters the same value? – Chris Dec 15 '22 at 10:44
  • Ok, I just checked it and I cannot two identical keys due to ```If multiple keyed nodes exist as children of another node, they must have unique keys.``` – Chris Dec 15 '22 at 10:53