解决是用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);

                },
     );
})
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐