为什么提供商有时不起作用?

发布于 2025-02-08 18:03:30 字数 4865 浏览 2 评论 0原文

提供商的行为非常奇怪,当添加产品时,Isempty属性会发生变化,但没有调用提供商,当删除产品时,称为提供商,该行为的原因是什么。 有一个带价格的按钮,当按下noincart时,该按钮会添加一个产品,并且按钮上的文字更改,如果有产品,则该按钮具有两个区域incart 代码>,左侧区域删除了产品,右侧添加了更多,如果单击左侧,则按需按下按钮更改。

class AllGoodsViewModel extends ChangeNotifier {

   var _isEmpty = true;
   bool get isEmpty => _isEmpty;

   void detailSetting(Goods item) {
      final ind = cart.value.indexWhere((element) => element.id == item.id);
      if (ind != -1) {
        changeButtonState(false);
      } else {
        changeButtonState(true);
      }
    }

   void changeButtonState(bool state) {
     _isEmpty = state;
     notifyListeners();
   }
}

// adds and reduces a product
  void haveItem({required Goods item, required int operation}) async {
    final ind = cart.value.indexWhere((element) => element.id == item.id);
    if (ind == -1) {
      final minCount = item.optState == 0 ? 1 : item.opt!.count;
      if (item.count < minCount) {
        //order.shake();
      } else {
        changeButtonState(false); --------- cart is not empty, not working
        cart.value.add(item);
        final ind = cart.value.length - 1;
        cart.value.last.isOpt = item.optState == 0 ? false : true;
        cart.value.last.orderCount = minCount;
        cart.value = List.from(cart.value);
        await SQFliteService.cart.addToCart(cart.value.last);
        changeCountInCart(operation);
      }
    }  else {
      final count = cart.value[ind].orderCount;
      if (count <= item.count) {} else { return; } //order.shake()
      if (operation < 0 || count + operation <= item.count) {} else { return; } //order.shake()
      changeButtonState(false); --------- cart is not empty, not working
      cart.value[ind].orderCount += operation;
      cart.value = List.from(cart.value);
      await SQFliteService.cart.updateItem(cart.value[ind].id, {"orderCount":cart.value[ind].orderCount});
      changeCountInCart(operation);
    }
  }
class _DetailGoodsPageState extends State<DetailGoodsPage> {

  GlobalKey _key = GlobalKey();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      Provider.of<AllGoodsViewModel>(context, listen: false).detailSetting(widget.item);
    });
  }


  @override
  Widget build(BuildContext context) {

    final model = Provider.of<AllGoodsViewModel>(context, listen: false);

    Widget inCart(){
      return GestureDetector(
          onPanDown: (details) {
            Goods? item = widget.item;
            RenderBox _cardBox = _key.currentContext!.findRenderObject() as RenderBox;
            final localPosition = details.localPosition;
            final localDx = localPosition.dx;
            if (localDx <= _cardBox.size.width/2) {
              Goods value = cart.value.firstWhere((element) => element.id == item.id);
              if (item.optState == 0 ? value.orderCount <= 1 : value.orderCount <= value.opt!.count) {
                setState(() {
                  final ind = cart.value.indexWhere((element) => element.id == item.id);
                  if (ind != -1) {
                    model.changeButtonState(true); ------ cart is empty it works
                    cart.value[ind].orderCount = 0;
                    SQFliteService.cart.delete(cart.value[ind].id);
                    cart.value = List.from(cart.value)..removeAt(ind);
                  }
                });
              } else {
                model.haveItem(item: item, operation: item.optState == 0 ? -1 : (-1 * value.opt!.count));
              }
            } else {
              model.haveItem(item: item, operation: item.optState == 0 ? 1 : item.count);
            }
          },
          child: ...
      );
    }

    Widget noInCart(){
      return Container(
        width: size.width - 16.w,
        margin: EdgeInsets.symmetric(vertical: 10.h),
        key: _key,
        child: TextButton(
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Design.appColor),
                padding: MaterialStateProperty.all(EdgeInsets.symmetric(vertical: 8.h, horizontal: 10.w)),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.h),
                ))
            ),
            onPressed: (){
              Goods? item = widget.item;
              model.haveItem(item: item, operation: item.optState == 0 ? 1 : item.count);
            },
            child: ...
        ),
      );
    }

 return ScreenUtilInitService().build((context) => Scaffold(
      backgroundColor: Colors.white,
      body: Container(
              height: 64.h,
              color: Colors.white,
              child: model.isEmpty ? noInCart() : inCart()
          )

The provider has a very strange behavior, when a product is added, the isEmpty property changes, but the provider is not called, and when the product is removed, the provider is called, what is the reason for this behavior.
There is a button with a price, when pressed noInCart, the button adds a product and the text on the button changes, if there is a product, then the button has two zones inCart, the left zone deletes the product and the right one adds more, if click on the left, the button changes as needed.

class AllGoodsViewModel extends ChangeNotifier {

   var _isEmpty = true;
   bool get isEmpty => _isEmpty;

   void detailSetting(Goods item) {
      final ind = cart.value.indexWhere((element) => element.id == item.id);
      if (ind != -1) {
        changeButtonState(false);
      } else {
        changeButtonState(true);
      }
    }

   void changeButtonState(bool state) {
     _isEmpty = state;
     notifyListeners();
   }
}

// adds and reduces a product
  void haveItem({required Goods item, required int operation}) async {
    final ind = cart.value.indexWhere((element) => element.id == item.id);
    if (ind == -1) {
      final minCount = item.optState == 0 ? 1 : item.opt!.count;
      if (item.count < minCount) {
        //order.shake();
      } else {
        changeButtonState(false); --------- cart is not empty, not working
        cart.value.add(item);
        final ind = cart.value.length - 1;
        cart.value.last.isOpt = item.optState == 0 ? false : true;
        cart.value.last.orderCount = minCount;
        cart.value = List.from(cart.value);
        await SQFliteService.cart.addToCart(cart.value.last);
        changeCountInCart(operation);
      }
    }  else {
      final count = cart.value[ind].orderCount;
      if (count <= item.count) {} else { return; } //order.shake()
      if (operation < 0 || count + operation <= item.count) {} else { return; } //order.shake()
      changeButtonState(false); --------- cart is not empty, not working
      cart.value[ind].orderCount += operation;
      cart.value = List.from(cart.value);
      await SQFliteService.cart.updateItem(cart.value[ind].id, {"orderCount":cart.value[ind].orderCount});
      changeCountInCart(operation);
    }
  }
class _DetailGoodsPageState extends State<DetailGoodsPage> {

  GlobalKey _key = GlobalKey();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      Provider.of<AllGoodsViewModel>(context, listen: false).detailSetting(widget.item);
    });
  }


  @override
  Widget build(BuildContext context) {

    final model = Provider.of<AllGoodsViewModel>(context, listen: false);

    Widget inCart(){
      return GestureDetector(
          onPanDown: (details) {
            Goods? item = widget.item;
            RenderBox _cardBox = _key.currentContext!.findRenderObject() as RenderBox;
            final localPosition = details.localPosition;
            final localDx = localPosition.dx;
            if (localDx <= _cardBox.size.width/2) {
              Goods value = cart.value.firstWhere((element) => element.id == item.id);
              if (item.optState == 0 ? value.orderCount <= 1 : value.orderCount <= value.opt!.count) {
                setState(() {
                  final ind = cart.value.indexWhere((element) => element.id == item.id);
                  if (ind != -1) {
                    model.changeButtonState(true); ------ cart is empty it works
                    cart.value[ind].orderCount = 0;
                    SQFliteService.cart.delete(cart.value[ind].id);
                    cart.value = List.from(cart.value)..removeAt(ind);
                  }
                });
              } else {
                model.haveItem(item: item, operation: item.optState == 0 ? -1 : (-1 * value.opt!.count));
              }
            } else {
              model.haveItem(item: item, operation: item.optState == 0 ? 1 : item.count);
            }
          },
          child: ...
      );
    }

    Widget noInCart(){
      return Container(
        width: size.width - 16.w,
        margin: EdgeInsets.symmetric(vertical: 10.h),
        key: _key,
        child: TextButton(
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Design.appColor),
                padding: MaterialStateProperty.all(EdgeInsets.symmetric(vertical: 8.h, horizontal: 10.w)),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.h),
                ))
            ),
            onPressed: (){
              Goods? item = widget.item;
              model.haveItem(item: item, operation: item.optState == 0 ? 1 : item.count);
            },
            child: ...
        ),
      );
    }

 return ScreenUtilInitService().build((context) => Scaffold(
      backgroundColor: Colors.white,
      body: Container(
              height: 64.h,
              color: Colors.white,
              child: model.isEmpty ? noInCart() : inCart()
          )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光礼记 2025-02-15 18:03:30

为了

更新

收听

Consumer<yourproviderclass>(
   builder: (context, yourproviderclassinstance, child) => widget,
 ),

in order to listen to updates you must have consumers

notifylistners function orders consumers to rebuild with the new data

wrap your widget with a consumer

Consumer<yourproviderclass>(
   builder: (context, yourproviderclassinstance, child) => widget,
 ),
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文