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

标签 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 ;
  });
}

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

谢谢!

最佳答案

您必须更改此:

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

关于dart - Dart:以String作为参数的函数作为回调中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55522961/

相关文章:

android-studio - 如何在 Flutter 中更改 Swiper 分页颜色?

listview - 在应用程序启动时,滚动到 ListView 中的最后一个元素

flutter - 在 Flutter 中为用户自动将可拖动对象移动到拖动目标

firebase - flutter 问题 : type 'Timestamp' is not a subtype of type 'DateTime'

flutter - 如何在 flutter 中设置 dispose() 后的状态?

dart - ListView.builder 不显示任何内容 - Flutter

intellij-idea - IntelliJ更新后我无法加载dart/flutter插件

flutter - 即使我使用了安全区域,容器1也没有偏离屏幕底部,这在带有弯曲边缘的手机中看起来更糟

dart - 如何使 TextFormField 文本在验证时显示在 TextFormField 行下方

dart - 无法在 DART 1.9.3、Polymer 0.16.1+2 中使用 initPolymer().run