Search code examples
androidsqliteflutterdartshopping-cart

How to update number of items count in cart?


I implement to add to cart functionality items added into cart successfully but the number of count in the cart badge is not updated when I reopen the application than the number of count updates can anyone help me?

AppBar(
        title: Text("Home Page"),
        backgroundColor: Color.fromRGBO(37, 36, 36, 9),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.only(right: 15, top: 10),
            child: InkWell(
              onTap: () {
                Navigator.push(context, new MaterialPageRoute<void>(
                  builder: (BuildContext context) {
                    return new Cart();
                  },
                ));
              },
              child: Badge(
                badgeContent: Text(
                  itemCount.toString(),
                  style: TextStyle(
                      fontFamily: 'Celias',
                      fontSize: 10,
                      color: Colors.white),
                ),
                badgeColor: Colors.green,
                child: Icon(
                  Icons.shopping_cart,
                  size: 30,
                ),
              ),
            ),
          ),

        ]);
void _getItemCount() async {
    counts = await db.getCartItemCount();
    setState(() {
      itemCount = counts;
    });
  }
Future<int> getCartItemCount() async {
    Database db = await this.database;
    return Sqflite.firstIntValue(await db.rawQuery("SELECT COUNT(*) FROM CART"));
  }

I am using badges: ^1.1.0 dependency for cart badge. I think the state is not updated every time that's why the count is not updated.


Solution

  • Imho, you could add await and then call _getItemCount()

    onTap: () async {
        await Navigator.push(context, new MaterialPageRoute<void>(
            builder: (BuildContext context) {
                return new Cart();
            },
        ));
        _getItemCount();
    }