Dart:以String作为参数的函数作为回调中的参数

时间:2019-04-04 18:42:51

标签: dart flutter

我正在学习Flutter,试图编写一个简单的计算器。我正在使用此代码构建行:

Row(    // creates row
mainAxisAlignment: MainAxisAlignment.spaceEvenly, //row is spaced evenly
children: <Widget>[
   _button("4", _number("4")), //calls _button widget passing String 4 and function _number, which passes string 4 also
   _button("5", _number("5")), //button with value 5
   _button("6", _number("6")), //button with value 6
   _button("-", _min("null")) //button for subtraction
  ],
),

我的_button小部件如下:

Widget _button(String number, Function() f(String number)){ //parameters: the button value as String and the function with the value as String
  return MaterialButton(
    height: buttonHeight,
    minWidth: buttonHeight,
    child: Text(number,
        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 48.0)),
    textColor: Colors.black,
    color: Colors.grey[100],
    onPressed: f,  //function is called
  );
}

现在,我想将字符串号传递给函数f,因此在调用函数_number时,它将获取字符串号并将其粘贴到显示器上:

void _number(String number){
  setState(() {
   display=display + number ;
  });
}

它不起作用,我试图解决它,但是没有成功。有人有主意吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

您必须更改此设置:

Widget _button(String number, Function() f(String number)){ //parameters: the button value as String and the function with the value as String
  return MaterialButton(
    height: buttonHeight,
    minWidth: buttonHeight,
    child: Text(number,
        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 48.0)),
    textColor: Colors.black,
    color: Colors.grey[100],
    onPressed: f,  //function is called
  );

为此:

Widget _button(String number, Function(String number) f){ //parameters: the button value as String and the function with the value as String
  return MaterialButton(
    height: buttonHeight,
    minWidth: buttonHeight,
    child: Text(number,
        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 48.0)),
    textColor: Colors.black,
    color: Colors.grey[100],
    onPressed: () {
       f(number); // function is called
    },  
  );

主要变化是参数放在Function(String param1, String param2) nameFunction内,在您的情况下为Function(String number) f

答案 1 :(得分:0)

对不起,但是您对javascript的了解似乎不够好,因为您应该传递对该函数的引用,而不是应该执行的调用

Widget _button(String number, Func){
//at onpressed add this
func(number);
}

然后这样称呼

_button("4", _number)