我正在观看《无聊的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)
然后我转换它吗?