My function that receives data =>
Future<Object?> GetTotal() async {
FirebaseDatabase database = FirebaseDatabase.instance;
DatabaseReference ref = FirebaseDatabase.instance.ref("Total");
DatabaseEvent event = await ref.once();
return event.snapshot.value;
}
And it's where I use it =>
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();
}
}),
It only fetches the data when the app is opened. But I want it to fetch the data every minute or every 10 minute how can I make it?
I think the problem is in GetTotal() function ref.once()
but what can I use instead of ref.once()
The solution here is to use a StreamBuilder. Every change in your "Total" node, will fire a new event, this will update the data that is shown by the 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"));
});