Dart空安全下非必填CallBack Function参数空报错解决方案问询
问题原因
The parameter 'OnPositionChangeCallback' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
上述报错的核心原因是Dart空安全规则约束:非可空类型的可选命名参数必须要么加required强制传入,要么设置非空默认值,否则可选参数隐式的默认null会和非空类型冲突。如果你不想将参数设为必填,可以选择以下两种方案解决:
可选解决方案
方案1:将参数声明为可空函数类型
在函数类型末尾添加?标记该参数可空,使用时通过安全调用符执行即可避免空异常。
改造后代码示例:class googleMapComponent extends StatefulWidget { // 类型后加?标记为可空 Function(LatLng pos)? OnPositionChangeCallback; googleMapComponent({ this.OnPositionChangeCallback, }); }回调调用示例:
// ?.call为安全调用,参数为空时自动跳过执行 OnPositionChangeCallback?.call(targetLatLng);方案2:给参数设置默认空回调
给可选参数指定一个匹配类型的无操作空函数作为默认值,无需修改参数可空性,调用时也不需要额外判空。
改造后代码示例:class googleMapComponent extends StatefulWidget { Function(LatLng pos) OnPositionChangeCallback; googleMapComponent({ this.OnPositionChangeCallback = (LatLng pos) {}, }); }如果你的Dart版本不支持直接将匿名函数作为默认值,可以改用静态常量空函数:
class googleMapComponent extends StatefulWidget { Function(LatLng pos) OnPositionChangeCallback; static void _emptyCallback(LatLng pos) {} googleMapComponent({ this.OnPositionChangeCallback = _emptyCallback, }); }
内容的提问来源于stack exchange,提问作者Ardeshir ojan
相关产品推荐
相关产品推荐

