skip to Main Content

These are the values read by sensor

enter image description here

Im trying to fetch these values from this database and use them in my application developed using flutter. But idk how. Any help is appreciated. language used is dart. I need to read four different values to four different variables

I tried many ways but ends up in error. i got one code thats not showing error but dont seem to read value


import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

final databaseReference = FirebaseDatabase.instance.ref().child('Sensor');

class Fetch {
  void getData() {
    DatabaseReference ref = FirebaseDatabase.instance.ref('Sensor/');
    ref.onValue.listen((DatabaseEvent event) {
      var temp = event.snapshot.value;
      print(temp);
    });
  }
}

3

Answers


  1. import 'package:firebase_database/firebase_database.dart';
    

    without listen:

    DatabaseReference refer = FirebaseDatabase.instance.ref('Sensor/');
    
    await refer.get().then((DataSnapshot data) async {
            print ( (data.value! as Map) ['gas'] ) 
                           ...
    

    with listen:

    refer.onValue.listen((DatabaseEvent event) {
          final Object? data = event.snapshot.value;
          print( (data as Map)['gas'] )
                     ...
    
    Login or Signup to reply.
  2. You can get Stream from FirebaseDatabase.instance.ref('Sensor/').onValue; and use StreamBuilder to display data. and you can separate the logic from UI code.

    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      late final stream = FirebaseDatabase.instance.ref('Sensor/').onValue;
    
      int counter = 0;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
              DatabaseReference ref = FirebaseDatabase.instance.ref('Sensor/');
              await ref.set({
                'dht11': 32 + counter++,
                'gas': 1152,
                'humidity': 71,
                'pressure': 1111.111,
              });
            },
          ),
          body: Column(
            children: [
              StreamBuilder(
                stream: stream,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    final data = snapshot.data?.snapshot.value as Map?;
                    if (data == null) {
                      return Text('No data');
                    }
                    final dht11 = data['dht11'];
                    final gas = data['gas'];
                    final humidity = data['humidity'];
                    final pressure = data['pressure'];
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('dht11: $dht11'),
                        Text('gas: $gas'),
                        Text('humidity: $humidity'),
                        Text('pressure: $pressure'),
                      ],
                    );
                  }
                  if (snapshot.hasError) {
                    print(snapshot.error.toString());
                    return Text(snapshot.error.toString());
                  }
    
                  return Text('....');
                },
              )
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
    1. First of all, to structure your db, you should use sensors instead of Sensor. Lowercase and plural. See more about structure data in Firebase Realtime Database: https://firebase.google.com/docs/database/flutter/structure-data
    2. Some remarks on your code:
    final databaseReference = FirebaseDatabase.instance.ref().child('Sensor'); <-- why do you define this without using it? 
    
    class Fetch {
      void getData() { <-- getData function does not have returned value, so when you call it, even it has data, you cannot retrieve them. 
        DatabaseReference ref = FirebaseDatabase.instance.ref('Sensor/'); <-- and you redefine ref here
        ref.onValue.listen((DatabaseEvent event) {
          var temp = event.snapshot.value;
          print(temp);
        });
      }
    }
    
    1. Data returned from Firebase Realtime DB will be viewed as Map in Flutter, so to access data, you will need to pass data as Map.
    • Use with listen:
    DatabaseReference ref = FirebaseDatabase.instance.ref("sensors");
    ref.onValue.listen((DatabaseEvent event) {
        final data = event.snapshot.value as Map;
    });
    
    • Use with async await:
      • Use with get():
      final ref = FirebaseDatabase.instance.ref();
      final snapshot = await ref.child('sensors/$sensorId').get();
      if (snapshot.exists) {
          final data = snapshot.value as Map;
      } else {
          print('No data available.');
      }
      
      • Use with once():
      DatabaseReference ref = FirebaseDatabase.instance.ref("sensors");
      final event = await ref.once(DatabaseEventType.value);
      final data = event.snapshot.value as Map;
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search