抖动重建导致数据更改

时间:2020-09-28 08:44:12

标签: flutter dart

我是Flutter和Dart的初学者,正在尝试构建一个使用SQFLite插件来持久保存数据的待办事项列表应用程序。我有一个任务列表(自定义类的对象),并试图为用户提供选择(通过下拉菜单)以选择特定任务类别的选项-类别ID存储为任务的属性。当我基于任务生成过滤列表并使用setState将我的类taskList设置为此生成的列表时,它会简单地重建为整个类列表。我不知道在哪里进行重建。

我的filterTasks函数采用一个类别名称,标识其类别ID-如果用户正在清除过滤器,则类别名称为”,然后循环遍历所有任务以找到ID匹配的位置(我意识到我可以还要对数据库执行此操作,并选择所有与ID匹配的位置,但即使这意味着它也应该起作用),如果存在匹配项,则它将显示的任务设置为此过滤列表。

void filterTasks(String category) async {
    await updateList(); //gets the entire list
    print('Mid ${this.taskList}');
    if (category != '') {
      int filteredId = await getCategoryId(category);
      List<Task> filtered = [];
      int count = taskCount;
      for (int i = 0; i < count; i++) {
        if (this.taskList[i].taskCategory == filteredId) {
          filtered.add(this.taskList[i]);
        }
      }
      if (filtered.isEmpty) {
        showSnackBar(context, "Error, no tasks of this category exist.", false);
        setState(() {
          categoryChoice = null;
        });
      } else {
        setState(() {
          this.taskList = filtered;
          this.taskCount = this.taskList.length;
          print('End ${this.taskList}');
        });
      }
    }
  }

更新列表功能只是从数据库中检索任务和类别的整个列表,因为用户可能希望直接在过滤器之间进行更改,而不必清洗过滤器。我将其设置为await,因为它是一个异步函数,并且我认为它可以在完成filterTasks函数后覆盖已过滤的列表。

这是我构建函数的初始部分,如果taskList或categoryList为null(在这里不是这种情况),我会在此调用更新列表。

Widget build(BuildContext context) {
    print('Start ${this.taskList}');
    if (taskList == null || categoryList == null) {
      taskList = List<Task>();
      categoryList = List<Category>();
      updateList();
    }
    return Scaffold()//my widget tree

调用该函数的下拉按钮的代码:

DropdownButton(
            hint: Text(
              'Filter',
              style: TextStyle(
                color: textColor,
              ),
            ),
            dropdownColor: bgColorPrimary,
            value: categoryChoice,//class variable
            items: this.categoryList?.map((Category instance) {
                  return DropdownMenuItem(
                      value: instance.categoryName,
                      child: Text(
                        instance.categoryName,
                        style: TextStyle(
                            color: categoryColorsMap[instance.categoryColour],
                            fontSize: 16.0),
                      ));
                })?.toList() ??
                [],
            onChanged: (newValue) {
              filterTasks(newValue);
            },
            icon: Icon(
              Icons.filter_list,
              color: textColor,
            ),
          )

过滤器列表由位于下拉按钮之后的另一个图标重置,该图标仅将categoryChoice设置为null(以显示下拉提示),并使用参数”调用filterTasks。

编辑: 在修改了一些打印语句后,尤其是4条,在代码段中显示了3条,在updateList函数的开始处显示了一条,现在,我变得更加着迷了。在updateList中的print语句只是说“已触发”,输出如下:

//APP BOOT UP
I/flutter (18734): Start null
I/flutter (18734): triggered
I/flutter (18734): Start [Instance of 'Task', Instance of 'Task', Instance of 'Task', Instance of 'Task']
//THIS IS WHEN I FILTERED THE TASKS
I/flutter (18734): triggered
I/flutter (18734): mid [Instance of 'Task', Instance of 'Task', Instance of 'Task', Instance of 'Task']
I/flutter (18734): End [Instance of 'Task', Instance of 'Task']
I/flutter (18734): Start [Instance of 'Task', Instance of 'Task']
I/flutter (18734): Start [Instance of 'Task', Instance of 'Task', Instance of 'Task', Instance of 'Task']

因此,当taskList进行更新时,不是updateList使其恢复为整个列表。我根本不知道该怎么做。任何帮助将不胜感激,谢谢。

PS我是dart的初学者,所以我对命名约定和更好的OOP细微差别并不完全熟悉,如果您对此有任何反馈,也请告诉我:)谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我终于解决了该错误,并且将其保留在此处,以防有人像我一样犯初学者的错误。正如我所怀疑的那样,问题出在updateList上,但后来排除在外(很大程度上是我自己的愚蠢),并且由于该函数由then语句组成,因此等待该函数不执行任何操作,并且一旦生成了filteredList,它就会很快替换为由updateList派生的整个列表。将updateList函数更改为async并使用await关键字意味着filterList仅在更新列表之后生成。

旧功能:

void updateList() {
    Future<Database> dbFuture = databaseHelper.initialiseDatabase();
    dbFuture.then((database) {
      Future<List<Task>> taskListFuture = databaseHelper.getTaskList();
      taskListFuture.then((taskList) {
        setState(() {
          this.taskList = taskList;
          this.taskCount = taskList.length;
        });
      });

      Future<List<Category>> categoryListFuture =
          databaseHelper.getCategoryList();
      categoryListFuture.then((categoryList) {
        setState(() {
          this.categoryList = categoryList;
          this.categoryCount = categoryList.length;
        });
      });
}

新功能:

 void updateList() async {
    Database db = await databaseHelper.initialiseDatabase();
    List<Task> taskTemp = await databaseHelper.getTaskList();
    List<Category> categoryTemp = await databaseHelper.getCategoryList();
    setState(() {
      this.taskList = taskTemp;
      this.taskCount = taskTemp.length;
      this.categoryList = categoryTemp;
      this.categoryCount = categoryTemp.length;
    });
  }

这已解决了过滤错误,希望它可以帮助陷入类似情况的其他任何人。谢谢所有尝试帮助我的人。