【问题标题】:Flutter - VoidCallback content is not executingFlutter - VoidCallback 内容未执行
【发布时间】:2018-09-16 14:05:51
【问题描述】:

我创建了以下客户小部件:

class MainButtonWidget extends StatelessWidget{
  String _text = "";
  TextTheme _textTheme = new TextTheme();
  IconData _icon = null;
  VoidCallback _onPressed;

  MainButtonWidget(String text, TextTheme textTheme, IconData icon, VoidCallback onPressed){
    _text = text;
    _textTheme = textTheme;
    _icon = icon;
    _onPressed = onPressed;
  }

  void setText(String text){
    _text = text;
  }

@override
Widget build(BuildContext context) {
  return new Container(
    child: new RaisedButton(
      padding: const EdgeInsets.fromLTRB(
          Dimens.edgeMainButtonLRB, Dimens.edgeMainButtonT,
          Dimens.edgeMainButtonLRB, Dimens.edgeMainButtonLRB),
      shape: new CircleBorder(side: new BorderSide(
          color: ColorRes.whiteTranslucent2,
          width: Dimens.widthSmallButtonHome)),
      onPressed: (){
        debugPrint("mainButtonWidget before _onPressed");
        _onPressed;
        debugPrint("mainButtonWidget after _onPressed");
        },
      color: Colors.transparent,
      child: new Column(
        children: <Widget>[
          new Icon(
            _icon,
            color: Colors.white,
          ),
          new Text(_text,
            style: _textTheme.button.copyWith(
              color: Colors.white,
            ),)
        ],
      ),
    ),
  );
}

}

这是我如何创建 MainButtonWidget 类型的对象:

Widget mapMainBtn = new MainButtonWidget('Map', textTheme, Icons.location_on, ()=> debugPrint("mapMainBtn -> onPressed called"));

按下按钮时似乎 VoidCallback 的内容没有执行。

在日志中显示以下消息: I/flutter (21436):_onPressed 之前的 mainButtonWidget I/flutter (21436):_onPressed 后的 mainButtonWidget

我希望在上述消息之间看到“mapMainBtn -> onPressed called”。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    _onPressed() 被调用。
    请看下面的代码:

    `onPressed: (){
     debugPrint("mainButtonWidget before _onPressed");
        _onPressed;
        debugPrint("mainButtonWidget after _onPressed");
    }`
    

    【讨论】:

    • 不,不是,因为缺少()。看我的回答
    • 谢谢!你说的对。我认为写 _onPressed 没有 '()' 就足够了。
    • 没有它只是对函数的引用,例如传递它以从其他地方调用,但调用是由()引起的
    【解决方案2】:

    需要调用()

    _onPressed();
    

    【讨论】:

    • 哇,太棒了。玩了 30 分钟...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2012-09-03
    • 2021-05-02
    • 2019-06-21
    • 1970-01-01
    相关资源
    最近更新 更多