繁体   English   中英

在 Dart 中,检查 class 是否继承父 class 并进行类型检查

[英]In Dart, check if a class inherits parent class with type checking

我试图找到一种安全的方法来使用 Flutter 中的 Bloc 模式,并进行非常强大的类型检查。

假设我们有这个简单的 Bloc 代码:

// States 

abstract class CourseState {}

class CourseInitialized extends CourseState {}

// Events 

abstract class CourseEvent {}

class CourseFetch extends CourseEvent {}

class CourseLoaded extends CourseEvent {}

// Bloc (somewhere in the Bloc)

final event = CourseFetch();

在 dart 中,我们可以使用is运算符来检查事件变量是CourseFetch还是CourseEvent类型:

event is CourseFetch // true
event is CourseEvent // true

但是没有什么能阻止我检查事件是否属于 CourseState 类型,甚至是 num、String 等类型。

event is CourseInitialized // false
event is String // false

当然,这种情况下的事件不能是字符串,因为它已经用 CourseFetch() class 进行了初始化。

我试图找到一种方法来禁止程序员(我们)错误地编写永远无法评估为 true 的 if 语句。

在我的情况下,我想有一种方法可以阻止我检查 IDE 中某种类型的state的变量事件并给我一条红色波浪线。

if (event is CourseInitialized) { 
// the above line should give me a warning, this variable event is not a State
}

有任何想法吗? 可以提供帮助的 Linting 工具或语法?

更新:我按照 Rémi 的建议尝试了 Freezed,它使代码变得简单并增加了安全的类型检查。 在这里,您可以找到 Bloc with Freezed and Built Value 的完整实现。

没有这样的事情(也不可能知道您检查了所有可能的情况)。

您可以做的是将is运算符替换为 function 为您执行此操作。

这方面的一个例子是代码生成器Freezed所做的。

代替:

abstract class CourseEvent {}

class CourseFetch extends CourseEvent {}

class CourseLoaded extends CourseEvent {}

你会写:

@freezed
abstract class CourseEvent with _$CourseEvent {
  factory CourseEvent.fetch() = _Fetch;
  factory CourseEvent.loaded() = _Loaded;
}

然后用作:

CourseEvent event;

event.when(
  fetch: () => print('Fetch event'),
  loaded: () => print('Loaded event'),
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM