【问题标题】:Provider not getting data from database提供者未从数据库中获取数据
【发布时间】:2021-10-19 05:06:39
【问题描述】:

我正在尝试制作一个简单的购物车应用程序,它可以从数据库中加载购物车数据。实际上将数据从数据库加载到提供者。但是当我们将商品添加到购物车并关闭应用程序时,当它回来时购物车没有任何商品。

调用fetchCartProducts 从数据库中获取数据,它必须给提供者cartItems。但它将数据存储在数据库中,关闭时不显示。

home_screen.dart

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Future<List<FoodItem>> _foodItems;

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

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('Food Cart'),
        actions: [
          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),
                    ),
                  );
                },
              ),
      ),
    );
  }
}



cart_provider.dart

class CartProvider with ChangeNotifier {
  Map<String, CartModel> _cartItems = {};

  Map<String, CartModel> get cartItems {
    return {..._cartItems};
  }

  int get itemCount {
    return _cartItems.length;
  }

  void reduceItem(
    String productId,
    String productName,
    int quantity,
    double price,
  ) {
    if (quantity == 1) {
      _cartItems.remove(productId);
      notifyListeners();
    } else {
      _cartItems.update(
        productId,
        (cartItem) => CartModel(
          productId,
          cartItem.price,
          productName,
          cartItem.quantity - 1,
        ),
      );

      notifyListeners();
    }
  }

  void addItem(String productId, String productName, double price) {
    if (_cartItems.containsKey(productId)) {
      //add quantity
      _cartItems.update(productId, (existingCartItem) {
        return CartModel(
          existingCartItem.id,
          existingCartItem.price,
          existingCartItem.productName,
          existingCartItem.quantity + 1,
        );
      });
    }
    notifyListeners();
  }

  void addToCart(
      String productId, String productName, int quantity, double price) {
    _cartItems.putIfAbsent(
      productId,
      () {
        DBHelper.insert('cart_food', {
          'id': productId,
          'productName': productName,
          'quantity': quantity,
          'price': price,
        });
        return CartModel(
          productId,
          price,
          productName,
          1,
        );
      },
    );

    notifyListeners();
  }

  double get totalAmount {
    var total = 0.0;
    _cartItems.forEach((key, cartItem) {
      total += cartItem.price * cartItem.quantity;
    });

    return total;
  }

  void removeItem(String productId) async {
    _cartItems.remove(productId);

    notifyListeners();
    await DBHelper.delete(productId);
  }

  Future<void> fetchCartProducts() async {
        List<Map<String, CartModel>> dataList = await DBHelper.getData('cart_food');
    print(dataList);

    //_cartItems = dataList.map((e) => )

    _cartItems = dataList as Map<String, CartModel>;

  }
}

获取数据


static Future<List<Map<String, CartModel>>> getData(String table) async {
    final db = await DBHelper.database();
    return db.query(table);
  }


我做错了什么?我不明白。请帮忙

【问题讨论】:

    标签: flutter dart sqflite


    【解决方案1】:

    数据是否成功上传到数据库?

    如果是这样,这就是可能出现的问题 - 您正在 initState() 中获取产品,如下所示:

    Provider.of<CartProvider>(context, listen: false).fetchCartProducts();
    

    这里的问题是“上下文”。 一般来说,对于一个小部件来说,初始化和监听来自网络的数据的最佳位置是 initState() 方法。但是“上下文”在 initState() 中不起作用,因为在调用 initState() 之后“上下文”开始发挥作用。所以,你不能在那里调用你的提供者类。 尝试使用 didChangeDependencies,如下所示:

    var _isInit=true;
    
        @override
          void didChangeDependencies() {
          if(_isInit){
             _foodItems = ApiService.getFoodItems();
             Provider.of<CartProvider>(context,listen:false).fetchCartProducts();
             _isInit=false;
          }
            super.didChangeDependencies();
        }
    

    Lmk 如果这可行。

    【讨论】:

    • 我试过这个,但之后我得到了这个错误。未处理的异常:“QueryResultSet”类型不是“List>”类型的子类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多