Home > Blockchain >  Icon value not updating with provider and sqflite in flutter
Icon value not updating with provider and sqflite in flutter

Time:10-21

I was making a simple cart app, it did well but cart count not showing when app is closed and reopened again.

I am using provider and calls fetchCartProducts() method when the app is opened. It calls fine. but cart badge widget itemcount is not changing at first time. only shows 0 at first time.

  Future<void> fetchCartProducts() async {
    final dataList = await DBHelper.getData('cart_food');

//convert dataList to  _cartItems

    final entries = dataList
        .map((item) => CartModel(
              item['id'],
              item['price'].toDouble(),
              item['productName'],
              item['quantity'],
            ))
        .map((cart) => MapEntry(cart.id, cart));

    _cartItems = Map<String, CartModel>.fromEntries(entries);
    print('inside fetchcart');
  }
class HomeScreen extends StatefulWidget 
{

  @override
  _HomeScreenState createState() => _HomeScreenState();

}

class _HomeScreenState extends State<HomeScreen> 
{

  Future<List<FoodItem>> _foodItems;
  var _isInit = true;

  @override
  void initState() {
    super.initState();
    _foodItems = ApiService.getFoodItems();
    Provider.of<CartProvider>(context, listen: false).fetchCartProducts();
    setState(() {});
  }

  @override
  void didChangeDependencies() 
  {

    if (_isInit) {
      Provider.of<CartProvider>(context).fetchCartProducts();
      _isInit = false;
      setState(() {});
    }
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final cart = Provider.of<CartProvider>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Food Cart'),
        actions: [
//this is not updating when the app is closed and opened again.
          Consumer<CartProvider>(
            builder: (_, cartprovider, ch) => Badge(
              child: ch,
              value: cartprovider.itemCount.toString(),
            ),
            child: IconButton(
              icon: Icon(Icons.shopping_cart),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (_) {
                    return CartScreen();
                  }),
                );
              },
            ),
          ),
        ],
      ),
      body: FutureBuilder<List<FoodItem>>(
        future: _foodItems,
        builder: (conext, snapshot) => !snapshot.hasData
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  FoodItem foodItem = snapshot.data[index];
                  return ListTile(
                    title: Text(foodItem.productName),
                    subtitle: Text(foodItem.variant),
                    trailing: IconButton(
                      onPressed: () {
                        cart.addToCart(
                          foodItem.storeid.toString(),
                          foodItem.productName,
                          1,
                          foodItem.price,
                        );
                        setState(() {});
                      },
                      icon: const Icon(Icons.shopping_cart),
                    ),
                  );
                },
              ),
      ),
    );
  }
}


otherwise when item added to cart, it working fine. the data loss when reopened. how to get total count when the app starts?

CodePudding user response:

In order to rebuild Consumer you need to call notifyListeners() inside your CartProvider

Add notifyListeners() to your fetchCartProducts() after assigning the value to _cartItems = Map<String, CartModel>.fromEntries(entries);

Future<void> fetchCartProducts() async {
    final dataList = await DBHelper.getData('cart_food');

//convert dataList to  _cartItems

    final entries = dataList
        .map((item) => CartModel(
              item['id'],
              item['price'].toDouble(),
              item['productName'],
              item['quantity'],
            ))
        .map((cart) => MapEntry(cart.id, cart));

    _cartItems = Map<String, CartModel>.fromEntries(entries);
    notifyListeners(); // <------- this line
    print('inside fetchcart');
  }
  • Related