【问题标题】:CallBack Function with null safety具有空安全性的回调函数
【发布时间】:2021-05-31 05:53:26
【问题描述】:

我有一个这样的小部件

class googleMapComponent extends StatefulWidget {
   Function(LatLng pos) OnPositionChangeCallback;

googleMapComponent({
this.OnPositionChangeCallback,})

使用 nullsafety 我得到这个错误

The parameter 'OnPositionChangeCallback' can't have a value of 'null' because of its type, but the implicit default value is 'null'.

我知道使用 required 会修复它,但我不希望它是必需的

【问题讨论】:

  • 您可以使用Function(LatLang? pos) 来允许空值或在传递值时使用! 运算符。
  • @DarShan 第一个解决方案不起作用,第二个解决方案我不想发送值,因为这个小部件有很多回调函数

标签: flutter dart-null-safety


【解决方案1】:

如果此函数是required,只需将参数设为必填,语言将强制您始终将函数传递给googleMapComponent 的构造函数

class googleMapComponent extends StatefulWidget {
   Function(LatLng pos) OnPositionChangeCallback;

googleMapComponent({required this.OnPositionChangeCallback,})

否则,使用 ? 关键字使函数可以为空。

这是这个问题的最终答案

final Function(LatLng pos)? OnPositionChangeCallback;

【讨论】:

  • 不,它不是必需的,对于第二种解决方案,你的意思是这样的 Function(LatLang?pos) 如果是,它也不起作用
  • 整个函数应该被标记为可为空的`Function(String pos) OnPositionChangeCallback`,而不仅仅是它的参数。请记住在使用前始终检查它是否不为空。这就是你要找的@Ardeshirojan?
  • 是的,这是正确的谢谢。我会用最终答案更新你的答案
猜你喜欢
  • 2020-10-14
  • 2021-08-12
  • 2015-04-01
  • 2021-04-28
  • 2021-09-22
  • 2021-08-09
  • 1970-01-01
  • 2021-03-30
  • 2021-06-12
相关资源
最近更新 更多