How can I read and increment a number (in this case order number) from firebase using flutter?

Viewed 78

I am using some of the following code to add an order to the Firebase Realtime Database using Flutter (Dart language) and this part is working.

    DatabaseReference _ref = FirebaseDatabase.instance.ref();
    final order = _ref.child('Orders');

  order.push().set({
        'orderNum': orderNum,
        'totalAmount': totalAmount,
        'dateTime': timeStamp.toString(),
        'cartProduct': cartProducts
            .map((cp) => {
                  'id': cp.id,
                  'title': cp.name,
                  'quantity': cp.quantity,
                  'price': cp.price
                })
            .toList()

I am then reading and attempting to alter the order number and incrementing it by one using the following

 String lastOrderNum = "";
  int intOrderNum = 0;
  String newOrderNum = "2";
  final DateTime dateee = DateTime.now();

  DatabaseReference _readRef = FirebaseDatabase.instance.ref();
  @override
  void initState() {
    super.initState();
    _activateListeners();
  }

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

I think the issue is with my child path which is (Orders/orderNum) which is missing a step in the path which is where the auto generated unique ID goes which come from the use of ".push()"

 order.push().set({

If I remove '.push()' and use my current path then the number auto increments but the previous order is overwritten.

The database entries look are as follows with order numbers being hardcoded:

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

How do I include the auto ID (example -N3ZdgEQIzsjLA5NCu3U) as part of my path , (Orders/???/orderNum)?

1 Answers
Related