无法按动按钮才能正常工作 [英] Can't get button press to work in flutter

查看:81
本文介绍了无法按动按钮才能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我是扑扑/飞镖的新手,所以对我轻松一点。我只是在尝试制作一个非常简单的应用,在该应用中,当您按下按钮时,会有一些文本更新告诉您按下按钮的次数。我不知道为什么这段代码不起作用。出现该按钮,但按此按钮无任何反应。

Ok I'm pretty new to flutter/ dart so go easy on me. I'm just trying to make a very simple app where when you press a button some text updates telling you how many times you have pressed the button. I have no idea why this code doesn't work. The button appears but nothing happens when you press it.

import 'package:flutter/material.dart';

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[],
    );
  }
}

class Buttonz extends StatefulWidget {
  @override
  _ButtonBeingPressed createState() => new _ButtonBeingPressed();
}

class _ButtonBeingPressed extends State<Buttonz> {
  int _timesPressed = 0;
  _buttonWasPressed() {
    setState(() {
      _timesPressed++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Column(children: <Widget>[
     new Center(
          child: new Row(
        children: <Widget>[
          new Text(
              'The button was pressed ' + _timesPressed.toString() + "         
 times"),
          new RaisedButton(
            onPressed: _buttonWasPressed(),
           child: new Row(
              children: <Widget>[new Text("Press meh")],
            ),
          ),
        ],
      ))
    ]);
  }
}


推荐答案

您的问题是您没有将回调传递给 RaisedButton ,而是调用了回调。

Your problem is that you didn't pass a callback to RaisedButton, you invoked your callback.

new RaisedButton(
  onPressed: _buttonWasPressed(), // invokes function
  child: new Row(children: <Widget>[new Text("Press meh")]),
);

要将回调传递给另一个小部件,您有两种选择:

To pass a callback to another widget you have two choices:

 new RaisedButton(
   onPressed: _buttonWasPressed, // no `()`,
   child: ...
 )



通过闭包



Pass a closure

 new RaisedButton(
   onPressed: () {
     // do something.
   },
   ..
 )

这篇关于无法按动按钮才能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆