【问题标题】:How to return an enum element from a class method?如何从类方法返回枚举元素?
【发布时间】:2019-10-25 19:54:29
【问题描述】:

我想从一个类方法中返回一个枚举元素,以便在其他类方法或函数中进一步使用它。我如何返回枚举元素或正确使用它以获得与在下面的非“分类”示例中使用它相同的结果?

enum colors { RED, GREEN }

class testClass {
  colors _color;

  colors get color {
    return _color;
  }

  void setColor(colors color) {
    _color = color;
  }
}

main() {
  void test(colors color) {
    switch (color) {
      case colors.RED:
        {
          print('RED');
        }
        break;
      case colors.GREEN:
        {
          print('GREEN');
        }
        break;
    }
  }

  test(colors.RED);

  testClass abc;
  abc.setColor(colors.GREEN);

  test(abc.color);
}

当我执行 Codesnipped 时,我的假设是,我得到了 RED 和 GREEN 的输出。相反,我得到以下信息:

$ dart test.dart

红色

未处理的异常: NoSuchMethodError:方法“setColor” 在 null 上调用。 接收方:空 尝试调用: setColor(Instance of '颜色')

【问题讨论】:

  • 因为你的 abc 对象为空?试试这个:testClass abc = testClass();

标签: flutter dart enums


【解决方案1】:

默认情况下,abc 的值被引用为 null。因为它没有初始化。 您需要初始化 abc 对象,如下所示:

testClass abc = testClass();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多