Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter TextFormField not updating value on rebuild

Tags:

flutter

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?

like image 578
Jonas Avatar asked Oct 11 '19 22:10

Jonas


1 Answers

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

like image 185
Pablo Barrera Avatar answered Sep 24 '22 17:09

Pablo Barrera