每当我设置状态时,Firebase数据加载

时间:2020-08-01 18:30:44

标签: firebase flutter google-cloud-firestore

我正在尝试使用类别列表构建应用程序。我想扩大所选类别并给其加粗的颜色。但是每次我设置状态时,它都会刷新屏幕,然后设置状态。每次设置状态后,我都可以停止刷新吗?

这是我的代码

这是我的未来

Future getCategories() async{
    var firestore = Firestore.instance;
    QuerySnapshot querySnapshot = await firestore.collection("category").getDocuments();
    return querySnapshot.documents;
  }

这是我未来的建设者

FutureBuilder(
    future: getCategories(),
    builder: (_, snapshot){
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Container(
          child: Text('Loading'),
        );
      }else return ListView(
          scrollDirection: Axis.horizontal,
          children:
          List.generate(snapshot.data.length, (int index) =>
              InkWell(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(snapshot.data[index].data["category"],
                        style: TextStyle(fontSize: currentCategory == snapshot.data[index].data["category"] ? sActive : sNotActive,
                          color: currentCategory == snapshot.data[index].data["category"] ? active : notActive,)
                      ,),
                  ),
                onTap: () {
                  String selectedCategory = snapshot.data[index].data["category"];
                  setState(() {
                    currentCategory = selectedCategory;
                    print(selectedCategory);
                  });
                },
              )));
    })

1 个答案:

答案 0 :(得分:1)

使用setState()时,整个小部件将重新生成,随后FutureBuilder会重新生成,getCategories()将再次调用getCategories()方法。

您可以在initState()中调用getCategories()方法(无需等待),将Future保存在状态类的属性中,然后在Future Builder中使用此属性,而不是{{1 }}。

另一种解决方案是将ListView()移动到单独的小部件中,因此,当您选择一个项目并调用ListView时,您只能重建setState

无论如何,您都可以使用BLoC pattern来管理状态,这样就无需重建整个小部件。