为什么我会收到此错误:_CastError(空检查运算符用于空值)

问题描述 投票:0回答:2

我有这样一个专栏:

  Column(children: [
    product.videos![product.videoIndex].videoUrl != null &&
            product.videos![product.videoIndex].videoUrl != ""
        ? VideoPlayerWidget(
            videoAddress: product.videos![product.videoIndex].videoUrl)
        : Image.asset('assets/images/video-placeholder.jpg'),
  ]),

我得到这个错误:

_CastError (Null check operator used on a null value)

我知道变量可能为空,这就是我将它们放在空检查 if 语句中的原因,但我不知道为什么会出现空检查错误以及如何通过它?

Flutter 迫使我将

!
放在空变量之后,然后它因此给我错误!

flutter if-statement casting nullable null-safety
2个回答
1
投票

这是因为

product.videos
null
,虽然如果它是
null
你处理了条件,但是你向
dart
编译器保证
product.videos
永远不会是
null
,通过使用
!
opeartor。把
!
改成
?
的意思,可能会是
null
,如果是
null
就要注意了。

通过将

!
替换为
?
来更改您的代码:

 product.videos?[product.videoIndex].videoUrl != null &&
            product.videos?[product.videoIndex].videoUrl != ""
        ? VideoPlayerWidget(
            videoAddress: product.videos![product.videoIndex].videoUrl)
        : Image.asset('assets/images/video-placeholder.jpg'),

编辑评论:

你能解释一下 ! 之间有什么区别吗?和 ?。和 ?和??

  1. !
    - 说编译器值永远不可能是
    null
    .
var val1 = val2! // val2 can never be null
  1. ?
    - 说编译器值可以是
    null
    .
String? val; // Here val can be potentially null
  1. ?.
    - 只有在不为空时才访问。
object?.prop1; // Here prop1 is accessed only if object is not null
  1. ??
    - 如果值为空则为替代值
var val1 = val2 ?? val3; // if val2 is null assign va13 to val1

0
投票

看起来你的

product.videos
本身
null
。所以在
!
条件下将
?
更改为
if

Column(children: [
    product.videos?[product.videoIndex].videoUrl != null &&
            product.videos?[product.videoIndex].videoUrl != ""
        ? VideoPlayerWidget(
            videoAddress: product.videos![product.videoIndex].videoUrl)
        : Image.asset('assets/images/video-placeholder.jpg'),
  ]),
© www.soinside.com 2019 - 2024. All rights reserved.