我有一个Dismissible
小部件列表如下:
Dismissible(
direction: DismissDirection.endToStart,
key: Key(widget.data[i]),
onDismissed: (direction) {
widget.onRemoveRequest(i, widget.data[i]);
},
background: Container(
color: Colors.red,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 20.0),
child: Text(
"Delete",
textAlign: TextAlign.right,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 16.0,
),
),
),
],
),
),
child: CustomTextField(
padding: const EdgeInsets.only(left: 30.0, right: 30.0),
hintText: widget.newEntryHint,
text: widget.data[i],
keyboardType: TextInputType.multiline,
onChanged: (val) {
widget.onChanged(i, val);
},
),
)
除了删除匹配对象外,它按预期工作。
注意:widget.onRemoveRequest
从源数据widget.data
中删除指定索引处的对象。
widget.data
是List<String>
。我提供这些作为key
,但每当我有两个匹配的字符串并解雇一个时,我得到一个错误,因为Dismissible
没有从树中删除(可理解)。
A dismissed Dismissible widget is still part of the tree.
因此,使用字符串列表,即使实际的字符串是 equal/match,我如何确保每个字符串都有唯一的键?
1 回答
您需要将每个数据分配给唯一标识符。足够独特的东西,不包含任何重复。然后,您可以将该唯一标识符与
Key
相关联。这不能仅使用
String
或Int
等原始对象来完成。您需要将数据映射到自定义对象。以下类是一个很好的例子:
这将允许您执行以下操作:
您可以使用UUID包或使用自定义算法(例如增量索引)为数据生成自定义 ID。
但请确保您的 ID 对于每个项目都是唯一的,并且在该项目的整个生命周期内保持不变(即使在更新后)。