我正在看无聊的Flutter 发展秀,在其中一集里,他们展示了BLOC的实现.

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

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

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

Switch表达式的类型"Type"不能分配给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');
      }
    }
  });

... 一切都很好,但我想知道是否有另一种方法可以切换Enum,以及为什么在这一行中使用局部变量storyType时,它会说没有使用它的值:

_storiesTypeController.stream.listen((storyType)

然后我把它换过来?

推荐答案

您有一个位于外部作用域的冗余变量:

final storyType = StoriesType.newStories;

由于_storiesTypeController.stream.listen的回调定义了名为storyType的新变量,因此不使用外部作用域中的变量.
您可以简单地删除冗余行:

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

你可以在Dart's language tour中找到更多关于switchcase的信息.

Dart相关问答推荐

Flutter Getx - 未找到Xxx.您需要调用Get.put(Xxx()) - 但我已调用 Get.put(Xxx())

禁用 ListView 滚动

默认情况下不可为空(Non-nullable ):如何启用experiment?

如何保存 List 并使用 Hive 检索?

如何将 Dart 代码迁移到不可空 (NNBD)?

在 Dart 中,List.unmodifiable() 和 UnmodifiableListView 有什么不同?

AnimatedContainer 可以为其高度设置动画吗?

Flutter:[cloud_firestore/unknown] NoSuchMethodError:null 上的无效成员:'includeMetadataChanges'(Flutter Web)

如何解决Id does not exist错误?

在Flatter中导航后,无法关注新页面中的文本字段

Flutter 如何使用 ListTile 三行

Flutter:如何获取assets目录中所有图像的名称列表?

GestureDetector onTap 卡

错误:default constructor is already defined

dart中的max/mi int/double 值是否有常数?

在 Dart 中,List.from 和 .of 以及 Map.from 和 .of 有什么区别?

如何在 Dart SDK 0.4+ 中使用 setInterval/setTimeout

Dart 中的 urlencoding

Dart 有没有办法测量小代码的执行时间

列出dart中双点(.)的使用?