我有以下场景:我想使用位于单独文件中的自定义 ButtonWidget。对于提取的 Button,我想移交在 onPressed 参数中使用的不同方法。以下是一些代码片段:
class DialogExample extends StatelessWidget {
const DialogExample({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
TextButton(
onPressed: () => myShowDialog(context), // works
child: const Text('Show Dialog'),
),
MyButton(receivedFunction: myShowDialog), // doesn't work
],
);
}
// The Method to be passed as an argument
Future<String?> myShowDialog(BuildContext context) {
return showDialog<String>(
// geht auch im Text ohne Typisierung
context: context,
barrierDismissible: false,
builder: (BuildContext context) => AlertDialog(
title: const Text('AlertDialog Title'),
content: const Text('AlertDialog description'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
),
);
}
}
带有自定义按钮的文件:
class MyButton extends StatefulWidget {
Future<String?> Function(BuildContext context) receivedFunction;
MyButton({super.key, required this.receivedFunction});
@override
State<MyButton> createState() => _MyButtonState();
}
class _MyButtonState extends State<MyButton> {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: widget.receivedFunction, // here I get a red underline with the error below.
child: Text("Externer Button"),
),
);
}
}
我收到此错误:
The argument type 'Future<String?> Function(BuildContext)' can't be assigned to the parameter type 'void Function()?'.
onPressed
参数需要一个void Function()
类型的参数,它不能被Future<String?> Function(BuildContext)
替代,所以撕开在这里不起作用。您可以传递一个匿名方法,该方法使用
receivedFunction
参数来调用 context
:
onPressed: () => widget.receivedFunction(context);