Stamp777
Stamp777

Reputation: 51

How do I get the key of my most recent push ID from Firebase Realtime Database in Flutter?

I am trying to get the most recent ID of from my orders table to that I can then use this ID in a path to get the order number and increment it by one.

  void _activateListeners() {

    final recentOrder = _readRef.child('Orders').limitToLast(1).get();
    final readOrder = _readRef
        .child('Orders/{$recentOrder}/orderNum')
        .onValue
        .listen((event) {
      final orderNum = event.snapshot.value;
      setState(() {
        lastOrderNum = orderNum.toString();
        intOrderNum = int.parse(lastOrderNum) + 1;
        newOrderNum = intOrderNum.toString();
      });
    });
  }

I know that I need to use the "key" word somehow but I have been unable to solve this problem.

my database table looks as follows:

Orders
    -N3ZdY6LOL_9Z-6KXHnK
              *cartProduct
              *dateTime:"2022-06-02 15:41:20.470139"
              *orderNum:"6"
              *totalAmount:45

   -N3ZdgEQIzsjLA5NCu3U
              *cartProduct
              *dateTime:"2022-06-02 15:41:20.470139"
              *orderNum:"7"
              *totalAmount:45

Edit: can someone tell me if it is even possible to fetch the unique push ID after it has been made (not directly after the order is added)? I have looked at all the documentation and I have failed to implement anything. I have also found numerous similar questions that are either just different or unanswered.

If I know SQL is SQLite a better alternative?

Upvotes: 1

Views: 861

Answers (1)

Victor Eronmosele
Victor Eronmosele

Reputation: 7696

You can get the key from the snapshot by using the snapshot's key property, like in this line below:

String? eventKey = event.snapshot.key;

Check out the documentation for Flutter's Realtime Database's DataSnapshot class for more information.

Upvotes: 1

Related Questions