【问题标题】:How to fix getters returning 'null' in Dart?如何修复在 Dart 中返回“null”的 getter?
【发布时间】:2020-02-03 11:46:57
【问题描述】:

我编写了一些代码,用于帮助使用自定义绘制工具可视化百分比,但有时百分比太小而无法正确显示,因此我决定制作一个方便地返回一个值的 getter,该值将被放入画家。

正如您在提供的代码中看到的那样,我尝试进行检查以检查数据是否尚未加载,并返回“0%”,这应该有效。

double get winPercent {
    var initalValue = _stats.winPercent.isNotEmpty ? _stats.winPercent : '0%';
    var calculateWinPrcnt = (double.parse(
          initalValue.substring(0, _stats.winPercent.length - 1),
        ) /
        100);

    if (calculateWinPrcnt < 5) {
      return 0.05;
    }
    return calculateWinPrcnt;
  }

如果 API 还没有数据,getter 应该返回 '0%',但我仍然收到输出为 null 的错误

The getter 'winPercent' was called on null.
Receiver: null
Tried calling: winPercent

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    “在 null 上调用了 getter 'winPercent'。”表示_stats 可能为空。你可以这样做:

    double get winPercent {
      // check for nulls
      final initialValue = (_stats?.winPercent?.isNotEmpty ?? false) ? _stats.winPercent : '0%';
      final value = initialValue.substring(0, initialValue.length - 1);
      final winPrcnt = (double.parse(value) / 100);
    
      if (winPrcnt < 0.05) {
        return 0.05;
      }
      return winPrcnt;
    }
    

    【讨论】:

      【解决方案2】:
      var _stats;
      
      if(_stats==null){
      
      _stats = className();
      
      }
      

      这里的问题在于调用 WinPercent 的对象为空尝试在调用 Api 之前初始化 _stats var _stats = YourModelClassName() 并且在获取 API 响应之后,您可以将该响应模型对象分配给 _stats。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-14
        • 2021-05-04
        • 2014-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多