【发布时间】:2021-06-28 00:30:45
【问题描述】:
因此,由于对该主题的一些很好的解释,我已经使用 Get_storage 找到了解决此问题的方法。我设法使用 getx 和 Provider 包在添加新内容时保存数据并在启动应用程序时读取它(这就是我在这里要采取的行为)。也就是说,我很难从内存中删除数据。
上下文
该项目是一个待办事项列表应用程序,前端运行良好,但在存储方面变得更加复杂。问题是我对颤振和移动开发非常陌生,我得到了一些帮助,但这种东西在我的脑海中仍然模糊不清,我无法使用相同的逻辑删除数据。当我像文档所说的那样调用 box.Remove('key') 时,我的整个列表都被删除了。我不知道为什么会这样。
所以我想知道我是否可以通过阅读更多解释来更多地理解它,我知道共享首选项在这种情况下非常有用,但我也会对使用 get_storage 的解决方案感到满意,因为我'我比较熟悉。
代码:\
我在 Provider 的帮助下在不同文件的 listView 中调用这些列表 - -
List<Task> _tasks = [
Task(
name: "Title",
description: "Description",
),
];
将任务添加到我的 ListView - -
void add(String newTitle, newDesc) {
final task = Task(name: newTitle, description: newDesc);
_tasks.add(task);
notifyListeners();
}
这里是从 ListView 中移除一个任务 - -
void removeTasks(Task task) {
_tasks.remove(task);
notifyListeners();
}
我尝试实现一个逻辑来写入和读取数据,它奏效了。但我也尝试通过调用 box.Remove('tasks'); 来使用这个 removeTasks 方法从存储中删除。 ('tasks' 是传递给写入和读取方法的键)。自从我的列表视图变空后,它从内存中删除了所有内容。
由于我没有那么有经验,我浏览了文档并且可以理解一些 SharedPreferences 解释(与 got_storage 相同),但我在尝试将其应用于我的代码时遇到了困难。
如果使用 get_storage 或共享偏好来解决此问题,我将不胜感激任何帮助。
我在哪里调用删除:
// bool variables that control the state of the screen
// since i can change it to show done tasks or on goind tasks
// dont mind that, i think its irrelevant to the problem.
//
bool isActiveDoing = true;
bool isActiveDone = false;
List finalArray = []; //it will store the tasks
class TaskList extends StatefulWidget {
@override
_TaskListState createState() => _TaskListState();
}
class _TaskListState extends State<TaskList> {
@override
Widget build(BuildContext context) {
//dont mind the if else as well, its not part of the problem
//just using it to handle the state of the screen
if (isActiveDoing) {
finalArray = Provider.of<TasksFunctions>(context).tasks;
}
//TasksFunctions is a class with methods on regards to the storage
//it contains add tasks, remove, etc... i'm using provider to
//link those to the screens with the notifyListeners
if (isActiveDone) {
finalArray = Provider.of<TasksFunctions>(context).doneTasks;
}
//now here is where i call the class tha has the deletion method
return Consumer<TasksFunctions>(
builder: (context, tasksFunctions, child) {
return ListView.builder(
//list view tha has all the tasks
itemCount: finalArray.length,
itemBuilder: (context, index) {
final task = finalArray[index];
//using the slidableWidget to wrap the deletion method
return SlidableWidget(
onDismissed: (action) {
if (isActiveDoing) {
Provider.of<TasksFunctions>(context, listen: false)
.removeTask(task);
//so here is where i'm deleting those tasks, calling that method
//listed up on this post
}
if (isActiveDone {
Provider.of<TasksFunctions>(context, listen: false)
.removeDone(task);
}
},
);
},
);
},
);
}
}
所以我花了一些时间翻译代码,但我认为它不符合 Flutter 的任何良好实践原则。
我也试过调用 storageList.remove(task);然后用 box.write('tasks', storageList); 重写它但没有从内存中删除任何内容(可能是因为我没有遍历整个 storageLists 来搜索我猜的正确索引)
【问题讨论】:
标签: list flutter dart sharedpreferences storage