0

//----- 当 Hive DB 中的产品数量增加或减少时,我正在尝试刷新 UI-----//

//---------------我的蜂巢类--------------------------//

@HiveType(typeId: 0)
class ProductDBModel extends HiveObject{
  @HiveField(0)
  int id;
  @HiveField(1)
  String productName;
  @HiveField(2)
  String image;
  @HiveField(3)
  int price;
  @HiveField(4)
  String description;
  @HiveField(5)
  int quantity;

  ProductDBModel(this.id, this.productName, this.image, this.price, this.description, this.quantity);
 
}

//--------------------我的购物车类我正在使用流生成器------------------ ------//

class CartScreen extends StatefulWidget {
  @override
  _CartScreenState createState() => _CartScreenState();
}

class _CartScreenState extends State<CartScreen> {
  Future<List> stream;

  @override
  void initState() {
    super.initState();
    stream = _openBoxgetList();
  }

  Future<List<ProductDBModel>> _openBoxgetList() async {
      Box hive_prod_box = await Hive.openBox<ProductDBModel>(ProductTable);
       List rawFavouriteList = await hive_prod_box.values.toList();
       return rawFavouriteList;
  }

  @override
  Widget build(BuildContext context) {  

    return StreamBuilder<List<ProductDBModel>>(
        stream: stream.asStream(),
        builder: (context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return Container(child: Center(child: CircularProgressIndicator()));
          }
          else if(snapshot.hasError){
            return Scaffold(body: Text('Error Occured while loading cart'),);
          }
          else
          {
            if(snapshot.data.length == 0){
              Hive.deleteFromDisk();
              return ShowEmptyCart();
            }
            else{
              return
                Scaffold(                 
                  body: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    child: ListView.builder(
                          physics: ScrollPhysics(),
                          shrinkWrap: true,
                          itemCount: snapshot.data.length,
                          itemBuilder: (context, index) {
                          
                            return Dismissible(
                              background: Container(color: Colors.red),
                              key: UniqueKey(),
                              onDismissed: (direction) {
                                snapshot.data[index].delete();
                              },
                              child: CartItem(snapshot.data[index], index),
                            );
                          },
                        ),
                  ),
                );
            }

          }
        });

  }

}

//-----------------购物车项目类更新产品数量-----------------//

class CartItem extends StatefulWidget {
  ProductDBModel prod_;
  int index;    
  CartItem(ProductDBModel this.prod_, this.index);    
  @override
  _CartItemState createState() => _CartItemState();
}

class _CartItemState extends State<CartItem> {
  CartScreen _cartScreen = new CartScreen();
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 5.0),
        child: Container(
          height: 150.0,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                    padding: const EdgeInsets.only(left: 10.0),
                    Container(
                          decoration: BoxDecoration(
                            color: grey_background,
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              InkWell(
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(8.0, 5.0, 8.0, 5.0),
                                  child: TextOnlyFont14(
                                      '-', Colors.black, FontWeight.w600),
                                ),
                                onTap: () {
                                  CheckUpdate(widget.prod_, widget.index, "dec", context);
                                },
                              ),
                              TextOnlyFont14(widget.prod_.quantity.toString(),
                                  Colors.black, FontWeight.w600),
                              InkWell(
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(8.0, 5.0, 8.0, 5.0),
                                  child: TextOnlyFont14(
                                      '+', Colors.black, FontWeight.w600),
                                ),
                                onTap: () {
                                  CheckUpdate(widget.prod_, widget.index, "inc", context);
                                },
                              ),
                            ],
                          ),
                        ),
                  ),
              
            ],
          ),
        ),
      ),
    );
  }

  Future<void> CheckUpdate(ProductDBModel product, int index_, String inc_dec,
      BuildContext context) async {
    Box prodBox = await Hive.openBox<ProductDBModel>(ProductTable);

    final modelExists = prodBox.containsKey(product.key);

    if (!modelExists) {
      product.quantity = 1;
      await prodBox.add(product);
    } else {
      if (equalsIgnoreCase(inc_dec, "inc")) {
        product.quantity += 1;
      } else if(equalsIgnoreCase(inc_dec, "dec")) {
        if (product.quantity == 1) {
        } else {
          product.quantity -= 1;
        }
      }
      else if(equalsIgnoreCase(inc_dec, "del")) {
        product.delete();
      }
      product.save();
    }

  }
}
4

0 回答 0