Flutter Firestore读取过多



我正在创建一个应用程序来向用户显示最新的燃油价格,我正在FirebaseFirestore数据库上使用快照侦听器,据我所知,只有当我更新数据库时,它才应该为每个用户创建1个读。。。我在一台设备上安装了它,并且为这台设备读取了33次!

连接到Firebase的代码是:

StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance
.collection('global')
.doc('inland')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text("Loading...",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
}
if (snapshot.hasError) {
return Text("Error",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
}
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Text("Loading...",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
} else {
Map<String, dynamic> document =
snapshot.data.data();
return Text("R " + document['95'],
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
}

它在AnimatedContainer中,但据我所知,当数据库中的价格不变时,应用程序会显示缓存中的价格,所以这应该没有什么区别。

我是不是理解错了什么?有办法解决这个问题吗?

每次flutter调用该小部件的build方法时,都会创建流,这可能需要很多次。构建方法应该是纯的,没有任何副作用*。换句话说,您不应该在构建方法中实例化昂贵的对象,比如流。您应该在外部创建对象,并将其传递给小部件。

为了解决这个问题,您可以创建一个有状态的小部件,在initState方法中,您应该初始化流,然后将其传递给StreamBuilder。

class StreamBuilderExample extends StatefulWidget {
@override
_StreamBuilderExampleState createState() => _StreamBuilderExampleState();
}
class _StreamBuilderExampleState extends State<StreamBuilderExample> {
Stream<DocumentSnapshot> firestoreStream;
@override
void initState() {
firestoreStream = FirebaseFirestore.instance.collection('global').doc('inland').snapshots();
super.initState();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: firestoreStream,
builder: (context, snapshot) {
// your code goes here
},
);
}
}
  • 参考:如何处理不需要的小部件构建

对于您问题的最后一点,Firestore只有在您告诉它这样做或没有互联网连接的情况下才会从缓存中读取。每次启动流或获取文档时,Firestore都会首先到达服务器,然后重新读取文档。尽管在流运行时,Firestore只会在查询的文档发生更改时进行更新。但如前所述,您会收到很多读取,因为每次构建小部件时都会重新创建流(这也可能是由热重新加载或简单地保存文件引起的(。

最新更新