图标值未随提供商和 sqflite 一起更新

Icon value not updating with provider and sqflite in flutter

我正在制作一个简单的购物车应用程序,它运行良好,但当应用程序关闭并再次打开时购物车计数不显示。

我正在使用提供程序并在应用程序打开时调用 fetchCartProducts() 方法。它很好。但是购物车徽章小部件 itemcount 第一次没有改变。第一次只显示0

  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),
                    ),
                  );
                },
              ),
      ),
    );
  }
}


否则当商品添加到购物车时,它工作正常。重新打开时数据丢失。如何在应用程序启动时获取总计数?

为了重建 Consumer,您需要在 CartProvider

中调用 notifyListeners()

将值分配给 _cartItems = Map<String, CartModel>.fromEntries(entries);

后,将 notifyListeners() 添加到您的 fetchCartProducts()
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');
  }