0

I am trying to create an Android app that can monitor sensor reading in real-time. This is the code I used for retrieving the data:

class _ReadPageState extends State<ReadPage>{
  String _displayText = 'results go here';
  final _database = FirebaseDatabase.instance.ref();
  FirebaseDatabase database = FirebaseDatabase.instance;


  @override
  void initState(){
    super.initState();
    _activateListeners();

  }

  void _activateListeners(){
    _database.child("temperature").onValue.listen((event){
      final temperature = event.snapshot.value;
      setState(() {
        _displayText = 'temperature= $temperature';
      });
    });
  }

When I run the app, it posts all of the data written in the realtime database like this enter image description here

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

Since you said that you want to get only the last updated record, then the simplest solution that you have is to sort the results of your query according to a timestamp field descending and call .limit(1). The sorting can be done on the client, or using the solution from my following answer:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Apparently the reason why I cannot use .limit(1) is because the structure of my database is wrong I think. My database receives data from node red using http request. It then stores all of the data into a single key called temperature. I want to make it so that whenever it receives a data, it creates a new key that I can use within the flutter. I hope you understand sir I am new to programming. – Mark Allen Molina Apr 26 '22 at 14:39
  • As far as I can see, you have added a call to `.child("temperature")`. This means that you can add a `.limit(1)` right after it. Is that correct? – Alex Mamo Apr 26 '22 at 14:46
  • It worked, sir! The only problem I have now is the auto-generated ID is still showing up and I don't need it to. I only need to show the numerical values. Is there anything I can do about that? Thank you very much for your response, it was a huge help. – Mark Allen Molina Apr 26 '22 at 17:45
  • Good to hear that. You're very welcome, Mark. In that case, simply use only the value that corresponds to the field. If you have a hard time implementing that, please post a new question, here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Apr 26 '22 at 19:10