解决flutter中使用provider报错This is likely caused by an event handler (like a button‘s onPressed) that cal

解决是用flutter报错:

======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
Tried to listen to a value exposed with provider, from outside of the widget tree.

This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.

To fix, write:
Provider.of<Cart>(context, listen: false);

It is unsupported because may pointlessly rebuild the widget associated to the
event handler, when the widget tree doesn't care about the value.

The context used was: Builder
'package:provider/src/provider.dart':
Failed assertion: line 265 pos 7: 'context.owner!.debugBuilding ||
          listen == false ||
          debugIsInInheritedProviderUpdate'

When the exception was thrown, this was the stack: 
#2      Provider.of (package:provider/src/provider.dart:265:7)
#3      WatchContext.watch (package:provider/src/provider.dart:636:21)
#4      _ProductDetailsState.build.<anonymous closure>.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter_app8/component/ProductDetails.dart:160:63)
#5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:991:20)
#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#e7266
  debugOwner: GestureDetector
  state: possible
  won arena
  finalPosition: Offset(293.1, 462.1)
  finalLocalPosition: Offset(28.7, 15.0)
  button: 1
  sent tap down
====================================================================================================

这个我在是用provider的时候,在按钮中是用了context.read方法读取provider的data时出现的,通过报错中很明显就可以看到是什么错误。他说是在类似与button这种不需要更改状态的不需要这种写法,建议是用Provider.of(context, listen: false)这种写法来处理,是用这种方法果然可以了

Builder(builder: (BuildContext context){
     return FlatButton(
                 child: Text("确定"),
                 onPressed: () {
                  //添加到购物车
                  if(_num>0){
                      Provider.of<Cart>(context, listen:false).add(Item(20.0, 1));
                  }
                  //关闭对话框并返回true
                  Navigator.of(context).pop(true);

                },
     );
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枣泥馅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值