我有一个看起来像这样的项目数组:
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);
});
}
这工作正常。但是,我希望用户能够撤消此操作。我的解决方案是执行以下操作:
- 让
removeItem
函数返回删除之前数组的外观:
Map<String, String> removeItemLiked() {
final removed = dateIdeas[index];
setState(() {
_controller.reset();
likes.add(dateIdeas[index]['Description']);
dateIdeas.removeAt(index);
});
return removed;
}
- 有一个
undo
函数,将项目添加回索引 0 处的数组中:
void undo() {
setState(() {
Map<String, String> result = removeItemLiked();
dateIdeas.insert(0, result);
});
}
这里的问题是,当触发undo
函数时,它也会重新触发removeItem
。如何将旧数组存储到变量中,以便以后始终可以使用它?
removeItem
在undo
函数中被你调用。 若要防止这种情况,请将函数调用与removed
变量分开。
// within stateful widget, declare 'removed'...
Map<String, String> removed;
您的其他函数会像这样修改;
void removeItemLiked() {
removed = dateIdeas[index];
setState(() {
_controller.reset();
likes.add(dateIdeas[index]['Description']);
dateIdeas.removeAt(index);
});
}
void undo() {
if(removed != null) {
setState(() {
dateIdeas.insert(0, removed);
});
}
}
您可以将删除的项目存储在变量(如lastRemoved
(中,并将其索引和值存储为两者。下面是一个简单的示例:
class MyNums {
List<int> numbers = [123, 34, 5, 436, 56, 677];
Map<String, dynamic> lastRemoved;
removeItem(int index) {
lastRemoved = {
'index': index,
'item': numbers[index],
};
numbers.removeAt(index);
}
undoRemove() {
if (lastRemoved != null) {
numbers.insert(lastRemoved['index'], lastRemoved['item']);
}
lastRemoved = null;
}
}
测试:
main() {
MyNums nums = MyNums();
print('initial:tt ${nums.numbers}');
nums.removeItem(2);
print('remove from index 2:t ${nums.numbers}');
nums.undoRemove();
print('undo index 2:tt ${nums.numbers}');
nums.removeItem(2);
print('remove from index 2:t ${nums.numbers}');
nums.removeItem(2);
print('remove from index 2:t ${nums.numbers}');
nums.undoRemove();
print('undo index 2:tt ${nums.numbers}');
nums.undoRemove();
print('nothing to undo:t ${nums.numbers}');
}
输出:
initial: [123, 34, 5, 436, 56, 677]
remove from index 2: [123, 34, 436, 56, 677]
undo index 2: [123, 34, 5, 436, 56, 677]
remove from index 2: [123, 34, 436, 56, 677]
remove from index 2: [123, 34, 56, 677]
undo index 2: [123, 34, 436, 56, 677]
nothing to undo: [123, 34, 436, 56, 677]