Search code examples
flutterdartdart-null-safety

Dart check nullable Type


I looking to find a way to check if the type is nullable using switch statement but I got an error by doing that. Doesn't anyone know how to check if the type of object in the nullable state?

void dataFactory(Type type, data){
    switch(type){
      case A:
        return A.fromJson(data);
        case A?: // Getting error Conditions must have a static type of 'bool'
          return A.fromJson(data);
      case B:
        return B.fromJson(data);
    }
  }

Solution

  • You can create a function Type getType<T>() => T;, but since getType<A?>() would not be considered a constant value, you would not be able to use it with a switch statement:

    Type getType<T>() => T;
    
    dynamic dataFactory(Type type, Map<String, dynamic> data) {
      if (type == A || type == getType<A?>()) {
         return A.fromJson(data);
      } else if (type == B) {
         return B.fromJson(data);
      }
      ...
    }
    

    Another approach would be to use a Map of callbacks:

    Type getType<T>() => T;
    
    final _factoryMap = <Type, dynamic Function(Map<String, dynamic>)>{
      A: A.fromJson,
      getType<A?>(): A.fromJson,
      B: B.fromJson,
    };
    
    dynamic dataFactory(Type type, Map<String, dynamic> data) =>
        _factoryMap[type]?.call(data);