【问题标题】:The operator '>=' can't be unconditionally invoked because the receiver can be 'null'. flutter null safety不能无条件地调用运算符“>=”,因为接收者可以为“null”。颤振零安全
【发布时间】:2021-07-12 10:46:43
【问题描述】:

我有以下代码

 if (myCart?.cart?.cartDetails != null &&
    myCart?.cart?.cartDetails!
            .indexWhere((element) => element.productId == productId)  >=
        0) {
  return true;
}

此代码在 ">=" 部分出现错误,表示它可以为空。 我该如何解决这个问题?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    indexWhere 在您的情况下可以返回 null 并且 >= 运算符不能与 null 值一起使用。试试下面的代码:

    final index = myCart?.cart?.cartDetails
        ?.indexWhere((element) => element.productId == productId);
    
    if (index != null && index >= 0) {
      return true;
    }
    

    【讨论】:

      【解决方案2】:

      我认为是因为 element.productId 可以为空。 你能试试 element.productId 吗? == productId 还是 element.productId? == 产品编号

      【讨论】:

        猜你喜欢
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 2021-08-18
        • 2021-09-05
        • 2021-09-16
        • 2022-01-12
        相关资源
        最近更新 更多