如何在Dart中启用枚举?

17

我正在观看《无聊的Flutter开发秀》,其中一集展示了Bloc的实现。

现在有一块代码,我认为最好用Switch语句替换,以防将来出现更多情况:

_storiesTypeController.stream.listen((storiesType) {
       if (storiesType == StoriesType.newStories) {
         _getArticlesAndUpdate(_newIds);
       } else {
         _getArticlesAndUpdate(_topIds);
       }
     });

...所以我尝试着去实现它,但是出现了一个错误:

类型 'Type' 的 switch 表达式不能赋值给 case 表达式的类型 'Stories Type'。

因此我想到了这个解决方法:

final storyType = StoriesType.newStories;

_storiesTypeController.stream.listen((storyType) {
    switch (storyType) {
      case StoriesType.newStories: {
        _getArticlesAndUpdate(_newIds);
      }
        break;
      case StoriesType.topStories: {
        _getArticlesAndUpdate(_topIds);
      }
        break;
      default: {
        print('default');
      }
    }
  });

...一切都正常工作,但我想知道是否有另一种方法来切换枚举,并且为什么它说本地变量storyType的值没有被使用,当我在这一行中使用它:

_storiesTypeController.stream.listen((storyType)

然后我转换它吗?

2个回答

18

您有一个生存在外部作用域中的冗余变量:

final storyType = StoriesType.newStories;
由于_storiesTypeController.stream.listen的回调定义了一个名为storyType的新变量,因此外部作用域的变量未被使用。
您可以简单地删除冗余行:
final storyType = StoriesType.newStories;

移除后,不应出现任何警告。
此外,在 switch 语句中不需要使用花括号。修改后的代码如下:

_storiesTypeController.stream.listen((storyType) {
    switch (storyType) {
      case StoriesType.newStories:
        _getArticlesAndUpdate(_newIds);
        break;
      case StoriesType.topStories:
        _getArticlesAndUpdate(_topIds);
        break;
      default:
        print('default');
    }
  });

您可以在Dart语言指南中了解更多关于switchcase的内容。


1

枚举类型的开关很容易,例如:

enum ActivityType {
  running,
  climbing,
  hiking,
  cycling,
  ski
}

extension ActivityTypeNumber on ActivityType {
  int get number {
    switch (this) {
      case ActivityType.running:
        return 1;
      case ActivityType.climbing:
        return 2;
      case ActivityType.hiking:
        return 5;
      case ActivityType.cycling:
        return 7;
      case ActivityType.ski:
        return 10;
    }
  }
}

更多关于枚举类型及其增强版本的使用方法


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接