Search code examples
dart

How do I check whether a generic type is nullable in 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
}

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


Solution

  • Try:

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