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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With