flutter - 如何在 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)
我切换它?
解决方案
您有一个位于外部范围内的冗余变量:
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
推荐阅读
- javascript - 当点击来自 v 按钮的链接时,Vuetify 工具提示会显示在左上角
- bash - 通配符在 bash 中表示任何但不为空
- python - 文件“kivy\properties.pyx”,第 864 行,在 kivy.properties.ObservableDict.__getattr__ AttributeError: 'super' object has no attribute '__getattr__'
- azure - Azure 函数 - 托管证书
- spring-boot - ZUUL API 网关 RIBBONCLIENT 请求错误
- javascript - 在子窗口中检测到查询参数后如何重新加载父窗口?
- javascript - 反应类组件。待办事项应用程序。如何使用 localStorage 存储数据
- flutter - 无法在警报对话框内容中加载资产
- sql - SQL 更新后触发器混淆
- vue.js - 断点未绑定,如何正确映射 webpack?