从firebase检索实时数据



我有一个颤振项目,用于接收来自firebase的湿度传感器数据。我正在上传数据到firebase,并试图在我的应用程序上检索它,但它只会在一段时间后检索数据。此外,在此之前,该值为空。而且,当更改时,应用程序上的数据不会发生变化。我如何获取数据,使其显示从我启动应用程序的那一刻起的数据,并在firebase上的数据更新时更改?这是我的密码。

double moistureData;
@override
bool _isLoading = false;
void initState() {
super.initState();
databaseReference.child('Data').once().then((DataSnapshot snapshot) {
int moisture = snapshot.value['Moisture'];
moistureData = moisture.toDouble();
print(moisture);
setState(() {
if (moistureData != null) {
_isLoading = true;
}
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Moisture'),
),
body: StreamBuilder(
stream: databaseReference.child('Data').child('Moisture').onValue,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
} else {
return Center(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text('$moistureData'),
RaisedButton(
child: Text('Refresh'),
onPressed: () {
setState(() {
databaseReference
.child('Data')
.once()
.then((DataSnapshot snapshot) {
int moisture = snapshot.value['Moisture'];
moistureData = moisture.toDouble();
});
});
},
)
],
),
),
);
}
}));

当然,从firebase加载数据、创建一个bool变量并将其设置为false需要一些时间。

double moistureData;
bool _isLoading=false;
@override
void initState() {
super.initState();
databaseReference.child('Data').once().then((DataSnapshot snapshot) {
final int moisture = snapshot.value['Moisture'];
moistureData=moisture.toDouble();
print(moisture);
setState((){
if(moistureData!=null)
_isLoading=true;
});
});
}

当_isLoading为false时,在小部件传递、循环进度指示器或空容器中。当它是真的时,调用其他内部的小部件。

要监听当前值和更新,需要观察查询对象的一个on...流属性。最接近您当前代码的是onValue流。

FlutterFire示例应用程序中的一个示例:

_counterRef.onValue.listen((Event event) {
setState(() {
_error = null;
_counter = event.snapshot.value ?? 0;
});
}

所以你看到这也使用了@satish的答案解释的setState(...)

最新更新