作为参数传递的 Future 函数不执行 Flutter

Future Function passed as parameter not executing Flutter

我正在尝试从自定义 Widget 创建一个 widget,因此当我将参数传递给创建 Widget 的函数时,我需要设置 onPressed 函数,但按下它时不起作用。

Class答:

final Future Function(BuildContext context, Key newKey, String title) myFunction = _functionToPass;
setState(() {
    _widgetList.add(_MyCustomWidget.createCustomWidget(_title, _isChecked, myFunction));
  });//This works, the widget appears on my screen.

  Future _functionToPass(BuildContext context, Key newKey, String taskTitle) =>
  showDialog(......);  
  

Class乙:

class MyCustomWidget {
  StatefulBuilder createCustomWidget(title, isChecked, myFunction) {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return ListTile(
            title: Text(title),
            leading: Checkbox(
              value: isChecked,
              onChanged: (bool? newValue) {
                setState(() {
                  isChecked = newValue!;
                });
              },
            ),
            trailing: TextButton(
              child: Icon(Icons.edit),
              onPressed: () async {
                print("Hi"); //This is printing correctly
                await myFunction; //the function is not calling
              },
            ),
          );
        });
  }
}

解决方案

您需要通过添加括号来调用您的函数,并传递所需的参数:

onPressed: () async {
  print("Hi");
  await myFunction(param1, param2...);   //Change this line
},

重现问题的示例:

dartpad.dev 上尝试 运行 下面的代码,带括号和不带括号:

void main() async {
  final Future Function(String title) myFunction = (String title) async{print(title);};
  print("Hi");
  await myFunction("a");
}

此外,正如评论中所讨论的,在方法句柄上指定带有参数的预期函数是一种很好的做法,而不是 os 只需命名参数,添加类型,如下所示:

StatefulBuilder createCustomWidget(title, isChecked, Future Function(BuildContext, Key, String) myFunction)

所以当你传递错误的参数时,Dart 知道这是错误的并警告你: