如何更新从 firebase 收到的数据

How can I update the data that received from firebase

我接收数据的函数=>

 Future<Object?> GetTotal() async {
      FirebaseDatabase database = FirebaseDatabase.instance;
    
      DatabaseReference ref = FirebaseDatabase.instance.ref("Total");
    
      DatabaseEvent event = await ref.once();
    
      return event.snapshot.value;
    }

这就是我使用它的地方=>

FutureBuilder(
                      future: GetTotal(),
                      builder: (context, snapshot) {
                        if (snapshot.hasError) {
                          print(snapshot.error);
                        }
                        if (snapshot.hasData) {
                          var data1 = snapshot.data!.toString();
                          var data2 = double.parse(data1);
                          String data3 = data2.toStringAsFixed(2);
                          return Text(
                            "Total Amount \n\n\n" + "${data3} TL",
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 24),
                          );
                        } else {
                          return CircularProgressIndicator();
                        }
                      }),

它只在打开应用程序时获取数据。但是我想让它每分钟或每 10 分钟获取一次数据,我该怎么做?

我认为问题出在 GetTotal() 函数 ref.once() 但我可以使用什么来代替 ref.once()

这里的解决方案是使用 StreamBuilder。 “总计”节点中的每个更改都将触发一个新事件,这将更新 StreamBuilder 显示的数据。

DatabaseReference ref = FirebaseDatabase.instance.ref("Totals");

StreamBuilder(
        stream: ref.onValue
        builder: (ctx, snapshot) {
          if (chatSnapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          // do something with the snapshot
          print(snapshot.snapshot.value); // this will show what is in the data you got
          return Container(child: Text("your data"));
        });