Home > OS >  show field from realtime database flutter
show field from realtime database flutter

Time:04-12

I'm still learning flutter and ,I want to get a value from Realtime database in firebase and then show it in the screen.

this is the full code , i can see the value in the terminal but when i dont know how to display it on the screen

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(
   
 ); 
}    
}

CodePudding user response:

You should instead use the StreamBuilder which allows you to consume the real-time stream from a Firebase collection or document.

In your case, your build method would've looked like this:


@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();
    }
  );
  • Related