我需要在运行时确定泛型类型是否是String、bool、int或double另一个类。我没有找到针对可为空类型执行此操作的方法:
class Foo<T> {
void foo() {
if (T == int) {
print("'T' is an int");
} else {
print("'T' is not an int");
}
}
}
void main() {
final foo = Foo<int>();
final bar = Foo<int?>();
foo.foo();
bar.foo();
}
Run Code Online (Sandbox Code Playgroud)
控制台输出:
// 'T' is an int
// 'T' is not an int
Run Code Online (Sandbox Code Playgroud)
是否有任何我不知道的语法来检查可为空类型?我已经尝试过,int?但它无法编译。
给定一些可为空的类型T?,如何获得相应的不可为空的类型T?
例如:
T? x<T extends int?>(T? value) => value;
Type g<T>(T Function(T) t) => T;
Type type = g(x);
print(type); // Prints "int?"
Run Code Online (Sandbox Code Playgroud)
现在我想获得不可为空的类型。我如何创建该函数convert以便:
Type nonNullableType = convert(type);
print(nonNullableType); // Prints "int"
Run Code Online (Sandbox Code Playgroud)