Flutter TextFormField重建时未更新值

问题描述 投票:0回答:1

我正在尝试编辑字符串列表。问题是,当我通过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('');
                });
              },
            )
          ],
        ),
      ),
    );

  }

任何想法?

flutter
1个回答
0
投票

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

key: ObjectKey(values[index])

这里是一个说明和示例,说明在这种情况下为什么需要添加密钥的原因:What are Keys in the Stateless widgets class?

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

更多信息:key property

© www.soinside.com 2019 - 2024. All rights reserved.