gpt4 book ai didi

Dart null 安全条件语句?

转载 作者:行者123 更新时间:2023-12-05 02:42:19 24 4
gpt4 key购买 nike

所以我有一个类Cache它有一个方法 compare返回 bool .

我有一个可以为 null 的此类的实例。

Cache? recent;

我想在 recent 时执行一段代码not null compare 返回 false

如果没有 null safety,我早就完成了

if(recent!=null && !recent.compare()){
//code
}

如何在启用空安全的情况下做同样的事情?

当我尝试上面的 null safety 时,我得到了

The method 'compare' can't be unconditionally invoked because the receiver can be 'null'.Try making the call conditional (using '?.') or adding a null check to the target ('!')

当我在下方尝试时

if(!recent?.compare()){
//code
}

它给了我

A nullable expression can't be used as a condition.Try checking that the value isn't 'null' before using it as a condition.

最佳答案

你可以通过以下方式解决这个问题

  • 使用局部变量(推荐)

    var r = recent; // Local variable
    if (r != null && !r.compare()) {
    // ...
    }
  • 使用 Bang 运算符 (!)

    if (!recent!.compare()) { 
    // ...
    }

关于Dart null 安全条件语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67669806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com