Dart:带有String作为参数的函数作为Callback中的参数

问题描述 投票:0回答:2

我正在学习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
  );
}

现在我想将String编号传递给Function f,所以当调用函数_number时,它会获取String编号并将其粘贴到显示器上:

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

它不起作用,我试图解决它,但没有成功。有没有人有想法?

谢谢!

dart flutter
2个回答
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


0
投票

对不起,但似乎你对javascript的了解不是很好,因为你应该传递对函数的引用而不是调用你应该做的是

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

然后这样称呼它

_button("4", _number)
© www.soinside.com 2019 - 2024. All rights reserved.