【问题标题】:Error calling 'Void' on 'onPressed/onTap' Flutter在“onPressed/onTap”Flutter 上调用“Void”时出错
【发布时间】:2019-04-18 18:30:43
【问题描述】:

在 onPressed/onTap 中调用 void 时出现错误

我正在尝试在继承的小部件/状态中调用设置状态 按照此说明 https://medium.com/flutter-community/widget-state-buildcontext-inheritedwidget-898d671b7956

在我不专业的眼里看起来他也在做同样的事情, 但显然我错过了一些东西; 你能帮帮我吗?

   class InhCore extends InheritedWidget {
  InhCore({Key key, @required Widget child, @required this.data})
      : super(key: key, child: child);

  final InhState data;

  @override
  bool updateShouldNotify(InhCore oldWidget) {
    return true;
  }
}

class InhWidget extends StatefulWidget {
  InhWidget({this.child});

  final Widget child;

  @override
  State<StatefulWidget> createState() => InhState();

  static InhState of(BuildContext context) {
    return (context.inheritFromWidgetOfExactType(InhCore) as InhCore).data;
  }
}

class InhState extends State<InhWidget> {
  final Map<String, int> cardMap = {
    'A':1,
    '2':2,
    '3':3,
    '4':4,
    '5':5,
    '6':6,
    '7':7,
    '8':8,
    '9':9,
    '10':0,
    'J':0,
    'Q':0,
    'K':0
  };

  List<String> cardDisplayed;

  void deal(String card) => setState(() => cardDisplayed.add(card));


  @override
  Widget build(BuildContext context) {
    return new InhCore(
      data: this,
      child: widget.child,
    );
  }
}

class CardButton extends StatelessWidget {
  final String input;
  CardButton({this.input});

  Widget build(BuildContext context) {
    final InhState state = InhWidget.of(context);
    return Container(
      width: 55.0,
      height: 55.0,
      child: Material(
        color: Colors.grey[200],
        child: InkWell(
          onTap: state.deal(input),
          child: Center (
            child:Text(input),
        ),
        ),
      ),
    );
  }
}

提前感谢您的帮助

【问题讨论】:

    标签: dart flutter void


    【解决方案1】:

    你错过了() =&gt;

    onPressed: () => state.deal(input)
    

    您的代码将调用state.deal(input) 的结果传递给onPressed,而上面的代码传递一个函数,该函数在调用时会调用state.deal(input)

    【讨论】:

    • 谢谢伙伴,它可以工作我显然还有其他问题与继承的小部件(我觉得超级酷),但当时只有一步:)
    • 这为我修复了它,但很奇怪我在其他地方有相同的设置(复制和粘贴),只有在我省略 () => 时才有效。显然我不明白其中的区别。
    • 我需要看一个具体的例子。对于事件处理程序,您总是需要() =&gt;(单语句短形式)或(){...}(块形式),除非调用“处理程序”返回一个成为实际事件处理程序的函数。
    猜你喜欢
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    • 2019-08-21
    • 1970-01-01
    • 2021-11-21
    • 2017-09-27
    相关资源
    最近更新 更多