SliverList没有在setState上更新为新列表

时间:2019-06-13 14:41:21

标签: flutter dart

我有一个SliverList,其中包含我在initState()中填充的子级。我有一个过滤器选项,可让我按子项的不同属性进行过滤。在initState中,我创建了4个不同的列表。一个未过滤的列表,两个已过滤的列表,然后一个listToShow,其中listToShow和未过滤的列表具有相同的元素。 ListToShow是我在屏幕上绘制的列表,当按下过滤器按钮时,我在setState()中将正确的过滤列表分配给listToShow。但是,列表不会在屏幕上更新。如果打印出这些值,则可以看到它发生了变化。

如果我尝试listToShow = [],则会在屏幕上显示一个空列表!我不知道怎么了。

bool filterByRisk = false;
bool filterByIssue = false;
Filter filter = new Filter();
List<ProjectCard> unfilteredList = new List();
List<ProjectCard> riskFilteredList = new List();
List<ProjectCard> issueFilteredList = new List();
List<ProjectCard> listToShow = new List();

@override
void initState() {
  for (Project project in portfolio.projects) {
    unfilteredList.add(ProjectCard(
      project: project,
    ));
    riskFilteredList.add(ProjectCard(
      project: project,
    ));
    issueFilteredList.add(ProjectCard(
      project: project,
    ));
    listToShow.add(ProjectCard(
      project: project,
    ));
  }
  riskFilteredList = filter.filterProject(riskFilteredList, 'risk');
  issueFilteredList = filter.filterProject(issueFilteredList, 'issue');
}


@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Color(0xFF1e9eb9),
    body: Stack(
      children: [
        CustomScrollView(
          controller: _scrollController,
          slivers: <Widget>[
            SliverAppBar(
              expandedHeight: 150,
              backgroundColor: Color(0xFF59c2cf),
              pinned: true,
              floating: false,
              title: Text(portfolio.name + "'s Portfolio"),
              flexibleSpace: FlexibleSpaceBar(
                collapseMode: CollapseMode.parallax,
                background: ClipPath(
                  clipper: MyClipper(),
                  child: Container(
                    color: Color(0xFF1e9eb9),
                  ),
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildListDelegate(
                createList(),
              ),
            ),
          ],
        ),
        _buildFab()
      ],
    ),
  );
}

List<ProjectCard> createList() {
  setState(() {
    if (filterByIssue) {
      listToShow = issueFilteredList;
    } else if (filterByRisk) {
      print("RISK");
      listToShow = riskFilteredList;
      for (ProjectCard p in listToShow) {
        print(p.project.name);
      }
    } else {
      listToShow = unfilteredList;
    }
  });
  return listToShow;
}

void issuePressed() {
  setState(() {
    filterByIssue = !filterByIssue;
  });
}

void riskPressed() {
  setState(() {
    filterByRisk = !filterByRisk;
  });
}

2 个答案:

答案 0 :(得分:0)

您可以尝试从createList()方法中删除setState吗,通常不建议在构建过程中执行setSet。

您不需要跟踪所有这些列表,有更好的方法,但除此之外,逻辑应该可以继续工作。我什么都没看到。

答案 1 :(得分:0)

尝试使用SliverFillRemaining

listToShow正文中设置setState变量。