Flutter:我可以将参数传递给按钮上的onPress事件中定义的函数吗? [英] Flutter: Can I pass arguments to a function defined in an onPress event on a button?

查看:627
本文介绍了Flutter:我可以将参数传递给按钮上的onPress事件中定义的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有按钮的简单表格,用于计算表格。我认为最好是单击按钮以开始计算并将变量传递给哑函数,而不是让该函数知道它不需要知道的文本字段。我可以这样做还是我的计算功能需要访问我的TextField?

I have a simple form with a button to calculate the form. I figure it's better to hit the button to start the action of calculating and pass the variables to the dumb function than to make the function aware of text fields it shouldn't need to know about. Can I do that or does my calculate function need to access my TextFields?

         new Container(
            color: Colors.grey.shade300,
            padding: new EdgeInsets.all(15.0),
            child: new Column(
              children: <Widget>[
                new TextField(
                  controller: _ageController,
                  decoration: new InputDecoration(
                      icon: new Icon(Icons.person_outline), labelText: "Age"),
                ),
                new TextField(
                  controller: _heightController,
                  decoration: new InputDecoration(
                      icon: new Icon(Icons.insert_chart),
                      labelText: "Height (in feet)"),
                ),
                new TextField(
                  controller: _weightController,
                  decoration: new InputDecoration(
                      icon: new Icon(Icons.line_weight),
                      labelText: "Weight (in lbs)"),
                ),
                new Padding(padding: new EdgeInsets.only(top: 20.0)),
                new RaisedButton(
                  onPressed: calculate(1, 2),
                  color: Colors.pinkAccent,
                  child: new Text(
                    "Calculate",
                    style: new TextStyle(color: Colors.white),
                  ),
                )
              ],
            ),
          ),

        ],
      ),
    );
  }

  void calculate(num1, num2) {

  }
}


推荐答案

例如

    int  result = 0;

    void calculate(num1, num2) {
     setState(() {
         result = num1 + num2;
     });
    }


    new RaisedButton(
          onPressed: () => calculate(1, 100),
          ...
    ),
    new Text("$result")

这篇关于Flutter:我可以将参数传递给按钮上的onPress事件中定义的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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