6

After upgrading to Flutter 1.25.0-8.1.pre null safety is enabled by default and I started to modify the code of my project. Everything is working fine except functions passed as parameters like in the following example:

class AppBarIcon extends StatelessWidget {
  final IconData icon;
  final Function onPressed;
  const AppBarIcon({Key? key, required this.icon, required this.onPressed}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      child: Icon(icon, size: 28, color: Colors.white),
      onPressed: onPressed,
    );
  }
}

onPressed is a required parameter so it cannot be null but nevertheless I get an error when trying to pass the function to the CupertinoButton:

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

I am already searching quite long for an answer and a possible solution but I haven't found one yet. Any help would be much appreciated.

Felix Mittermeier
  • 183
  • 1
  • 2
  • 11

3 Answers3

7

You are passing a Function() value to a void Function() parameter like it says. Change your declaration to final void Function() onPressed; so that the typing is a closer match and can't possibly return a null or take args.

Brad
  • 121
  • 1
  • 8
Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
  • Yes you always need to add the void keyword before `Function`, even though dart static analysis does not give an error. – Joran Aug 15 '21 at 19:14
4

You could have just added the parenthesis to the function declaration like so, Function() the updated code is below.

class AppBarIcon extends StatelessWidget {
  final IconData icon;
  final Function() onPressed;
  const AppBarIcon({Key? key, required this.icon, required this.onPressed}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      child: Icon(icon, size: 28, color: Colors.white),
      onPressed: onPressed,
    );
  }
}
IBRAHIM ALI MUSAH
  • 831
  • 10
  • 19
3

Use VoidCallback instead of void Function(), and create your own for the ones which isn't defined.

class FooWidget extends StatelessWidget {
  final VoidCallback onPressed; // Required
  final Widget Function(BuildContext context) builder; // Required 
  final VoidCallback? onLongPress; // Optional (nullable)

  FooWidget({
    required this.onPressed, 
    required this.builder, 
    this.onLongPress, 
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPressed,
      onLongPress: onLongPress,
      child: builder(context),
    );
  }
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440