解决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
·
解决是用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);
},
);
})
更多推荐
已为社区贡献7条内容
所有评论(0)