如何检查Dart NNBD中的通用类型是否可为空?

如何检查Dart NNBD中的通用类型是否可为空?

问题描述:

比方说,我有一些函数采用通用类型作为参数.如何在该函数中检查泛型类型参数是否可为空?我想做这样的事情:

Let's say I had some function that takes a generic type as an argument. How do I check within that function whether the generic type argument is nullable or not? I want do something like this:

void func<T>() {
  print(T is nullable);
}

void main(){
  func<int>(); //prints false
  func<int?>(); //prints true
}

我唯一想做的就是检查 T.toString()是否以?结尾,这很hacky.

All I can think of to do is to check if T.toString() ends with a ? which is very hacky.

尝试:

bool isNullable<T>() => null is T;