3

Error in onPressed Trying to pass onPressed Function but getting Error.

Error - The argument type 'Function' can't be assigned to the parameter type 'void Function()?'. enter image description here

class CircleButton extends StatelessWidget {
  CircleButton({required this.icon, required this.onPressed});
  final IconData icon;
  final Function onPressed;                 [![Error][1]][1]//Here
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: Icon(icon),
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        elevation: 6.0,
        primary: Color(0xFF4C4F5E),
        shape: CircleBorder(),
        padding: EdgeInsets.all(15),
      ),);
  }}
Yash kolte
  • 117
  • 1
  • 9
  • 2
    Does this answer your question? [The argument type 'Function' can't be assigned to the parameter type 'void Function()?' after null safety](https://stackoverflow.com/questions/64484113/the-argument-type-function-cant-be-assigned-to-the-parameter-type-void-funct) – Md. Yeasin Sheikh Feb 21 '22 at 15:04

2 Answers2

7

The Function type is actually a dynamic Function type.

The ElevatedButton expects a void Function to its onPressed method, which there is actually a type that is a typedef for it: VoidCallback

So, replace your Function onPressed with VoidCallback onPressed.

Miguel Ruivo
  • 16,035
  • 7
  • 57
  • 87
1

Change Function to VoidCallback

class CircleButton extends StatelessWidget {
  CircleButton({required this.icon, required this.onPressed});
  final IconData icon;
  final VoidCallback onPressed;   //Change Function to VoidCallback
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Icon(icon),
      style: ElevatedButton.styleFrom(
        elevation: 6.0,
        primary: Color(0xFF4C4F5E),
        shape: CircleBorder(),
        padding: EdgeInsets.all(15),
      ),
    );
  }
}
Yash kolte
  • 117
  • 1
  • 9