在具有空安全性的颤振中将函数作为参数传递

Passing a function as parameter in flutter with null safety

升级到Flutter 1.25.0-8后1.pre null safety是默认开启的,我开始修改我项目的代码。一切正常,除了作为参数传递的函数,如下例所示:

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 是必需的参数,因此它不能为空,但是当我尝试将函数传递给 CupertinoButton 时出现错误:

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

我已经为答案和可能的解决方案搜索了很长时间,但我还没有找到。任何帮助将不胜感激。

您正在将 Function() 值传递给 void Function() 参数,就像它说的那样。将声明更改为“final void Function() onPressed;”这样打字是更接近的匹配并且不可能 return null 或 take args.

您可以像这样在函数声明中添加括号,Function()更新后的代码如下。

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,
    );
  }
}

使用 VoidCallback 而不是 void Function(),并为未定义的创建您自己的。

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),
    );
  }
}