我有一系列看起来像这样的物品:
final List<Map<String, String>> dateIdeas = [
{'Description': 'Drink Cocktails','Image': 'assets/images/cocktailsfull.jpg'},
{'Description': 'Go for dinner!', 'Image': "assets/images/dinner.jpg"},
];
当用户点击按钮时,第一项将从数组中删除。
removeItem() {
setState(() {
dateIdeas.removeAt(index);
});
}
这可以正常工作。但是,我希望用户能够撤消此操作。我对此的解决方案是执行以下操作:
- Have the
removeItem
function return what the array looked like before the removal:
Map<String, String> removeItemLiked() {
final removed = dateIdeas[index];
setState(() {
_controller.reset();
likes.add(dateIdeas[index]['Description']);
dateIdeas.removeAt(index);
});
return removed;
}
- Have an
undo
function that adds the item back into the array at index 0:
void undo() {
setState(() {
Map<String, String> result = removeItemLiked();
dateIdeas.insert(0, result);
});
}
The issue here is that when triggering the undo
function it also retriggers removeItem
. How can I have the old array stored to a variable so I can always use it later on?
The
removeItem
is getting called by you within theundo
function. To prevent this, separate the function call from theremoved
variable.您的其他函数将像这样被修改;
You can store the removed item in a variable like
lastRemoved
and store it's index and value both. Here's a simple example:测试:
输出: