Flutter TextFormField 在重建时不更新值

Jon*_*nas 4 flutter

我正在尝试使编辑字符串列表成为可能。问题是,当我通过 删除列表项时IconButton,TextField 会重建但不知何故仍具有旧值。通过调试,我发现我的字符串列表已正确更新,这意味着已删除的字符串实际上已在我的列表中删除。

这是我的代码:

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('');
                });
              },
            )
          ],
        ),
      ),
    );

  }
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Pab*_*era 6

您需要像这样向 TextFormField 添加一个键:

key: ObjectKey(values[index])
Run Code Online (Sandbox Code Playgroud)

这是一个解释和一个示例,说明在这种情况下需要添加键的原因:无状态小部件类中的键是什么?

键是颤振引擎在识别列表中的哪个小部件已更改的步骤中使用的东西

更多信息: 关键属性