flutterdartdart-null-safety

The argument type 'Function' can't be assigned to the parameter type 'void Function()?' after null safety


I want to achieve to make a drawer with different items on it, so I am creating a separate file for the DrawerItems and the with the constructor, pass the data to the main file. But I get the following error on the onPressed function:

"The argument type 'Function' can't be assigned to the parameter type 'void Function()'"
class DrawerItem extends StatelessWidget {
    
      final String text;
      final Function onPressed;
    
      const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return FlatButton(
          child: Text(
            text,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 18.0,
            ),
          ),
          onPressed: onPressed,
        );
      }
    }

Anyone knows why?


Solution

  • Change your code to accept a VoidCallback instead of Function for the onPressed.
    By the way VoidCallback is just shorthand for void Function() so you could also define it as final void Function() onPressed;

    Updated code:

    class DrawerItem extends StatelessWidget {
        
          final String text;
          final VoidCallback onPressed;
        
          const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
        
          @override
          Widget build(BuildContext context) {
            return FlatButton(
              child: Text(
                text,
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 18.0,
                ),
              ),
              onPressed: onPressed,
            );
          }
        }