Home > Blockchain >  Why the provider sometimes does not work?
Why the provider sometimes does not work?

Time:06-21

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()
          )

CodePudding user response:

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,
 ),
  • Related