名称“string”不是类型,不能在“is”表达式中使用

TSR*_*TSR 7 dart flutter

在对返回不同类型对象的函数进行单元测试时,我需要检查返回对象的类型是否与预期相同。因此,我需要在变量内传递多个类。然后我需要将此变量与is运算符一起使用来检查类型。

final string = String;
assert('foo' is string);
Run Code Online (Sandbox Code Playgroud)

但我越来越

error: The name 'string' isn't a type and can't be used in an 'is' expression. 
Run Code Online (Sandbox Code Playgroud)

我在某处读到一个名为的库Dart:mirrors可以解决这个问题,但我还没有看到一个实际的例子。

TSR*_*TSR -1

我找到了答案。创建我想要断言的类型的实例,然后使用runtimeType属性的技巧。

如果从a.dart调用一个类,User并且从b.dart调用另一个类User,则runtimeType将不一样

final string = 'anything'.runtimeType;
assert('foo'.runtimeType is string);
Run Code Online (Sandbox Code Playgroud)