Flutter Dart:不带运行函数的返回变量
我有一个如下所示的项目数组:Flutter Dart:不带运行函数的返回变量,flutter,dart,Flutter,Dart,我有一个如下所示的项目数组: final List<Map<String, String>> dateIdeas = [ {'Description': 'Drink Cocktails','Image': 'assets/images/cocktailsfull.jpg'}, {'Description': 'Go for dinner!', 'Image': "assets/images/dinner.jpg"}, ]; 这是正确的。但是,我希望
final List<Map<String, String>> dateIdeas = [
{'Description': 'Drink Cocktails','Image': 'assets/images/cocktailsfull.jpg'},
{'Description': 'Go for dinner!', 'Image': "assets/images/dinner.jpg"},
];
这是正确的。但是,我希望用户能够撤消此操作。我的解决方案是执行以下操作:
removietem
函数返回数组在删除之前的样子:这里的问题是,当触发
undo
功能时,它还会重新触发removietem
。如何将旧数组存储到变量中,以便以后可以始终使用它?您将在undo
函数中调用removietem
。
为防止出现这种情况,请将函数调用与已删除的变量分开
// within stateful widget, declare 'removed'...
Map<String, String> removed;
您可以将删除的项存储在变量中,如lastRemoved
,并同时存储其索引和值。下面是一个简单的例子:
类MyNums{
列表编号=[123,34,5436,56677];
地图删除;
removeItem(内部索引){
最后删除={
“索引”:索引,
“项”:数字[索引],
};
数字。删除(索引);
}
撤消删除(){
如果(lastRemoved!=null){
插入(lastRemoved['index'],lastRemoved['item']);
}
lastRemoved=null;
}
}
测试:
main(){
MyNums nums=MyNums();
打印('首字母:\t\t${nums.numbers}');
移动项目(2);
打印('remove from index 2:\t${nums.numbers}');
nums.undoRemove();
打印('undo index 2:\t\t${nums.numbers}');
移动项目(2);
打印('remove from index 2:\t${nums.numbers}');
移动项目(2);
打印('remove from index 2:\t${nums.numbers}');
nums.undoRemove();
打印('undo index 2:\t\t${nums.numbers}');
nums.undoRemove();
打印('无需撤消:\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]
void undo() {
setState(() {
Map<String, String> result = removeItemLiked();
dateIdeas.insert(0, result);
});
}
// 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);
});
}
}
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]