How do I check whether a generic type is nullable in Dart NNBD?

Viewed 1871

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.

4 Answers

Try:

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

I have come across this a lot. And @Irn method works, except for when T is type Type (when using generics), it will always return saying that T is not null.

I needed to test the actual type of Type not Type its self.

This is what I have that is working really well for me.

bool get isNullable {
  try {
    // throws an exception if T is not nullable
    final value = null as T;
    return true;
  } catch (_) {
    return false;
  }
}

The accepted answer really just checks if the type can be null. It doesn't care about the type that you are operating the null operator on.

If you want to check if a type is a specific nullable type, a.k.a if you want to check if a type is specifically one of type DateTime? and not String?, you can't do this in dart via T == DateTime? as this conflicts with ternary operator syntax.

However, since dart allows passing nullable types into generic arguments, it's possible to it like so:

bool isType<T, Y>() => T == Y;

isType<T, DateTime?>() works.

It creates a new List instance to verify if it's type is nullable or not by using the is operator which supports inheritance:

bool isNullable<T>() => <T?>[] is List<T>;
Related