I have the following scenario: I want to use a custom ButtonWidget which is located in a sperate file. To that extracted Button, I want to hand over different methods to be used in the onPressed parameter there. Here are some code snippets:
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'),
),
],
),
);
}
}
The file with the custom button:
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"),
),
);
}
}
I got this error:
The argument type 'Future<String?> Function(BuildContext)' can't be assigned to the parameter type 'void Function()?'.
The
onPressedparameter is expecting an argument of typevoid Function(), which is not substitutable by aFuture<String?> Function(BuildContext), so a tear-off won't work here. You can pass an anonymous method that callsreceivedFunctionwith thecontextparameter instead: