首页 > 解决方案 > 如何在 Dart 中打开枚举?

问题描述

我正在观看 The Boring Flutter Development Show,其中一集中他们展示了 Bloc 的实现。

现在有这段代码,我认为最好用 Switch 语句替换,你知道,以防将来出现更多情况:

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

...所以我尝试实现它,但它给了我一些错误说

开关表达式的类型“类型”不能分配给案例表达式的类型“故事类型”。

所以我想出了这个解决方法:

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');
      }
    }
  });

...并且一切正常,但我想知道是否有另一种方法来切换 Enum 以及为什么它说局部变量 storyType 的值没有被使用,当我在这一行中使用它时:

_storiesTypeController.stream.listen((storyType)

我切换它?

标签: flutterdartswitch-statement

解决方案


您有一个位于外部范围内的冗余变量:

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 的语言之旅switch中找到更多信息。case


推荐阅读