Custom-Button-Widget with dynamic onPressed Callback-Method

46 views Asked by At

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()?'.
1

There are 1 answers

0
Dhafin Rayhan On

The onPressed parameter is expecting an argument of type void Function(), which is not substitutable by a Future<String?> Function(BuildContext), so a tear-off won't work here. You can pass an anonymous method that calls receivedFunction with the context parameter instead:

onPressed: () => widget.receivedFunction(context);