显示来自实时数据库的字段 flutter

show field from realtime database flutter

我还在学习 flutter,我想从 firebase 的实时数据库中获取一个值,然后在屏幕上显示它。

这是完整代码,我可以在终端中看到该值,但是当我不知道如何在屏幕上显示它时

class Body extends StatefulWidget {
  
@override
  BodyState createState() => BodyState();

}
class BodyState extends State<Body> {


final db = FirebaseFirestore.instance;
late final reference = FirebaseDatabase.instance.ref();
late DatabaseReference databaseReference ; 

  @override
  Widget build(BuildContext context)  {
     
  DatabaseReference tempvaleur =
        FirebaseDatabase.instance.ref('temperature/esofostemperature0/valeur');
      tempvaleur.onValue.listen((DatabaseEvent event) async {
   
     print(event.snapshot.value); 
     final data = event.snapshot.value ; 
     
    
}
   );
 return Column(
   
 ); 
}    
}

您应该改用 StreamBuilder,它允许您使用来自 Firebase 集合或文档的 real-time 流。

在您的情况下,您的 build 方法将如下所示:


@override
  Widget build(BuildContext context)  {

  DatabaseReference tempvaleur =
        
  FirebaseDatabase.instance.ref('temperature/esofostemperature0/valeur');

  return StreamBuilder(
    stream: tempvaleur.onValue,
    builder: (context, snapshot) {
       
      if (snapshot.hasData) {
         // consume your data here
         var data = (snapshot.data! as DatabaseEvent).snapshot.value;
         
         // hoping your value is a string, but just in case...
         return Text(data.toString());
      }

      return CircularProgressIndicator();
    }
  );