Home > Blockchain >  Dart check nullable Type
Dart check nullable Type

Time:07-29

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);
    }
  }

CodePudding user response:

You question is:

I looking to find a way to check if the type is nullable using switch statement. Doesn't anyone know how to check if the type of object in the nullable state?

Even though I didn't use the switch statement I guess you can use this answer and verify if a generic type is nullable by creating a new list instance.

Note: I'm assuming we can replace the Type type parameter instance with a generic type T. Since Flutter disable reflections this is the only way we can use in order to verify a given type T nature (Nullable or not).

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

You can also maybe adapt this function to fill your needs:

bool checkTypes<X, Y>() => <X>[] is List<Y> && <Y>[] is List<X>;

And use it as:

T dataFactory<T>(dynamic data) {
  if(checkTypes<T, A>()) {
    // Non-nullable [A]
  } else if(checkTypes<T, A?>()) {
    // Nullable [A]
  }

  /// Repeat with [B], [C], etc.
}

You can also test it:

void main() {
  print(checkTypes<A, A>()); // true
  print(checkTypes<B?, B>()); // false
  print(checkTypes<B?, B?>()); // true
}

CodePudding user response:

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, 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(dynamic)>{
  A: A.fromJson,
  getType<A?>(): A.fromJson,
  B: B.fromJson,
};

dynamic dataFactory(Type type, dynamic data) => _factoryMap[type]?.call(data);

CodePudding user response:

Just use the null keyword here:

switch(type){
      case A:
        return A.fromJson(data);
        case null:
          return A.fromJson(data);
      case B:
        return B.fromJson(data);
    }
  • Related