每次我设置状态时都会加载Firebase数据



我正在尝试构建一个带有类别列表的应用程序。我想把所选的类别做得更大,并给它一个大胆的颜色。但每次我设置状态时,它都会刷新屏幕,然后设置状态。每次设置状态时,我能阻止它刷新吗?

这是我的代码

这是我未来的

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);
});
},
)));
})

当您使用setState()时,整个小部件将重建,随后FutureBuilder将再次调用getCategories()方法。

您可以在initState()中调用getCategories()方法(无需等待(,并将future保存在状态类的属性中,然后在future生成器中使用此属性,而不是getCategories()

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

无论如何,您可以使用例如BLoC模式来管理状态,这样您就不需要重新构建整个小部件。

最新更新